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++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read