Open In App

C++ Program For Iterative Quick Sort

Last Updated : 25 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Quicksort also known as partition-exchange sort is a divide-and-conquer sorting algorithm that works by selecting a pivot element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot element. The sub-arrays can then be sorted in the same way and this continues till the sub-arrays only consist of a single element.

In C++, quicksort can be implemented using both recursively and iteratively. In this article, we will learn how to implement quicksort in C++ iteratively.

Partition Process

In quicksort, the key process is partition, which sorts the array such that all the elements to the left of the pivot are smaller than or equal to the pivot and all the elements to the right of the pivot are greater than the pivot in case of increasing order. This function has the time complexity of O(n) and space complexity of O(1). This function returns the sorted position of the pivot in the array.

Algorithm of Partition

The partition process algorithm can be written as:

1. Set pivot  = arr[last].
2. Set i = first.
3. Initiate a loop with variable j = i first to last - 1. In Loop,
      a. If arr[j] < pivot, swap arr[i] and arr[j] and increment i by 1.
      b. Else, continue.
4. After loop, swap arr[i] and pivot.
5. Return i.

Here, the first and last are the index of the first and last element of the array.

For Decreasing order, we do the comparison arr[j] > pivot. This process is actually the same as that of recursive quicksort.

QuickSort Working

The quicksort works by repeatedly dividing the array into two subarrays around the pivot position returned by the partition funciton. The working of the quicksort algorithm is:

  1. We first select a pivot and use the partition function.
  2. The partition function will return the correct position of the pivot.
  3. We divide the array into two subarrays around this pivot.
  4. For each subarray, we repeat steps 1 to 3 till we get the subarrays with only single elements.
  5. After that, the array will already be in the sorted order.

Algorithm for the Iterative Quicksort

After understanding the quicksort, we will see how we can implement quicksort using loops:

1. Initialize stack with size = end - start + 1.
2. Push first and last in the stack.
3. Now, till the stack is empty, do
     a. Set last = stack[top] and pop stack.
     b. Set first = stack[top] and pop stack.
     c. Call pivot_pos = partition(arr, first, end)
     d. If pivot_pos - 1 > first.
          i. push first to stack.
          ii. push pivot_pos - 1 to stack.
     e. If pivot_pos + 1 < last.
          i. push pivot_pos + 1 to stack.
          ii. push last.

C++ Program for Iterative QuickSort

C++




// C++ program to implement the iterative quicksort
#include <bits/stdc++.h>
using namespace std;
  
// Function to swap two elements
void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}
  
// partition process
int partition(int arr[], int first, int last)
{
    int pivot = arr[last];
  
    int i = first;
    for (int j = first; j < last; j++) {
        if (arr[j] <= pivot) {
            swap(&arr[i], &arr[j]);
            i++;
        }
    }
    swap(&arr[i], &arr[last]);
    return (i);
}
  
// iterative quick sort
void quickSortIterative(int arr[], int first, int last)
{
    int stack[last - first + 1];
    int top = -1;
    stack[++top] = first;
    stack[++top] = last;
    while (top >= 0) {
        last = stack[top--];
        first = stack[top--];
        int pivot_pos = partition(arr, first, last);
  
        // If there are elements on left side of pivot, then
        // push left side to stack
        if (pivot_pos - 1 > first) {
            stack[++top] = first;
            stack[++top] = pivot_pos - 1;
        }
  
        // If there are elements on right side of pivot,
        // then push right side to stack
        if (pivot_pos + 1 < last) {
            stack[++top] = pivot_pos + 1;
            stack[++top] = last;
        }
    }
}
  
// driver code
int main()
{
    int size = 10;
    int arr[size] = { 10, 23, 4, 0, 8, 5, 9, 11, 22, 3 };
  
    quickSortIterative(arr, 0, size - 1);
  
    cout << "Elements after sorting:";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
  
    return 0;
};


Output

Elements after sorting:0 3 4 5 8 9 10 11 22 23 

Complexity Analysis

Time Complexity

  1. Average Case: θ (N log(N)
  2. Worst Case: O (N2)

Space Complexity

  1. Average Case: θ (N)
  2. Worst Case:  O (1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads