C++ Program For Iterative Quick Sort
Last Updated :
25 Nov, 2023
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:
- We first select a pivot and use the partition function.
- The partition function will return the correct position of the pivot.
- We divide the array into two subarrays around this pivot.
- For each subarray, we repeat steps 1 to 3 till we get the subarrays with only single elements.
- 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;
};
OutputElements after sorting:0 3 4 5 8 9 10 11 22 23
Complexity Analysis
Time Complexity
- Average Case: θ (N log(N)
- Worst Case: O (N2)
Space Complexity
- Average Case: θ (N)
- Worst Case: O (1)
Similar Reads
C++ Program For Radix Sort
Radix Sort is a sorting technique in which we sort the elements by processing each and every digit of that element. It is not a comparison-based sorting algorithm which means we do not compare the elements in a radix sort in order to sort them. Here, we apply counting sort to every digit of an eleme
5 min read
C++ Program for Bitonic Sort
Bitonic Sequence: A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that x0 <= x1 â¦..<= xi and xi >= xi+1â¦.. >= xn-1 A sequence, sorted in increasing order is cons
4 min read
sort_heap function in C++
The sort_heap( ) is an STL algorithm which sorts a heap within the range specified by start and end. Sorts the elements in the heap range [start, end) into ascending order. The second form allows you to specify a comparison function that determines when one element is less than another. Defined in h
3 min read
qsort() Function in C
The qsort() in C is a library function used to sort an array of items in ascending order or descending order. It stands for "quick sort," as it implements the quicksort algorithm for sorting which is one of the fastest and most efficient algorithms to sort the array.Let's take a look at an example t
4 min read
Implement Quicksort with first element as pivot
QuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the pivot. There are many different versions of quickSort that pick the pivot in different ways. Always pick the first element as a pivot.Always pick the last element as a pivot.Pick a
13 min read
Internal Working of sort() in C++
In C++, sort() is an STL function used for sorting containers such as arrays, vectors, etc. It provides an efficient and versatile way to sort data in C++. In this article, we will learn how the sort() function internally works.The sort() function uses the algorithm named IntroSort for sorting the g
5 min read
Comparator Function of qsort() in C
In C, qsort() is used for sorting an array in desired order. But to provide compatibility to different data types, it additionally requires a comparator function to determine the order of how to arrange the elements.Let's take a look at an example:C#include <stdio.h> #include <stdlib.h>
3 min read
Map and External Sorting Criteria/Comparator in C++ STL
C++ Map is another commonly used STL container, it stores elements in a mapped fashion. Each element is stored as a pair having a key value and a mapped value. No two mapped values can have the same key values which means each key is unique. By default, key values in the map are in lexicographically
4 min read
std::forward_list::sort() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of
3 min read
std::partial_sort_copy in C++
std::partial_sort is used for sorting the range within the entire container. So, if we want to keep the original container intact and just copy the sorted sub-part of the container into another one, then for that purpose, we can use std::partial_sort_copy. Just like std::partial_sort, partial_sort_c
4 min read