C++ Quick sort Exercise: Sort a collection of integers using the Quick sort
12. Sort a Collection Using the Quick Sort Algorithm
Write a C++ program to sort a collection of integers using Quick sort.
Sample Solution:
C++ Code :
#include <iostream>
// Function to perform quick sort
void quick_Sort(int *nums, int low, int high) {
    // Initializing indices and pivot
    int i = low;
    int j = high;
    int pivot = nums[(i + j) / 2];
    int temp;
    // Partitioning step of the quicksort algorithm
    while (i <= j) {
        // Finding elements less than the pivot on the left side
        while (nums[i] < pivot)
            i++;
        // Finding elements greater than the pivot on the right side
        while (nums[j] > pivot)
            j--;
        // Swapping elements to maintain order
        if (i <= j) {
            temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
            i++;
            j--;
        }
    }
    // Recursive calls for the remaining partitions
    if (j > low)
        quick_Sort(nums, low, j);
    if (i < high)
        quick_Sort(nums, i, high);
}
// Main function
int main() {
    // Initializing an array of integers for sorting
    int nums[] = {125, 0, 695, 3, -256, -5, 214, 44, 55};
    // Calculating the number of elements in the array
    int n = sizeof(nums) / sizeof(nums[0]);
    // Displaying the original numbers in the array
    std::cout << "Before Quick Sort:" << std::endl;
    for (int i = 0; i < n; ++i)
        std::cout << nums[i] << " ";
    // Calling the quicksort function
    quick_Sort(nums, 0, n - 1);
    // Displaying the sorted numbers after Quick Sort
    std::cout << "\nAfter Quick Sort:" << std::endl;
    for (int i = 0; i < n; ++i)
        std::cout << nums[i] << " ";
    return (0);
}
Sample Output:
Before Quick Sort: 125 0 695 3 -256 -5 214 44 55 After Quick Sort: -256 -5 0 3 44 55 125 214 695
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to implement quick sort with randomized pivot selection and print pivot choices.
 - Write a C++ program to implement quick sort using the Lomuto partition scheme and count recursive calls.
 - Write a C++ program to implement quick sort and handle duplicate pivot elements gracefully.
 - Write a C++ program to implement quick sort and display each partitioning step during the recursion.
 
Go to:
PREV : Sort a Collection Using the Pancake Sort Algorithm.
 NEXT :  Sort a Collection Using the Radix Sort Algorithm.
C++ Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
