Quick Sort Algorithm
Quick Sort Algorithm
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into
smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the
specified value, say pivot, based on which the partition is made and another array holds values greater
than the pivot value.
Quicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays.
This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are
O(n2), respectively.
The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-lists until
all lists contains only one element.
while True do
while A[++leftPointer] < pivot do
//do-nothing
end while
swap leftPointer,right
return leftPointer
end function
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified
expert to boost your career.
Analysis
The worst case complexity of Quick-Sort algorithm is O(n2). However, using this technique, in average
cases generally we get the output in O (n log n) time.
Implementation
Following are the implementations of Quick Sort algorithm in various programming languages −
Open Compiler
#include <iostream>
using namespace std;
#define MAX 7
int intArray[MAX] = {4,6,3,2,1,9,7};
void display() {
int i;
cout << "[";
while(true) {
while(intArray[++leftPointer] < pivot) {
//do nothing
}
cout << "\npivot swapped : " << intArray[leftPointer] << "," <<
intArray[right] << endl;
swap(leftPointer,right);
cout << "Updated Array: ";
display();
return leftPointer;
}
int main() {
cout << "Input Array: ";
display();
quickSort(0, MAX-1);
cout << "\nOutput Array: ";
display();
}
Output
Input Array: [4 6 3 2 1 9 7 ]
Output Array: [1 2 3 4 6 7 9 ]