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 random element as a pivot.
Pick the median as the pivot.
Note: Here we will be implementing quick sort by picking the first element as the pivot.
The key function in quick sort is a partition. The target of partitions is to put the pivot in its correct position if the array is sorted and the smaller (or equal) to its left and higher elements to its right and do all this in linear time.
Partition Algorithm:
There can be many ways to do partition, the following pseudo-code adopts the method given in the CLRS book.
We start from the leftmost element and keep track of the index of smaller (or equal) elements as i.
While traversing, if we find a smaller (or equal) element, we swap the current element with arr[i].
Otherwise, we ignore the current element.
Pseudo Code for recursive QuickSort function:
// low –> Starting index, high –> Ending index
quickSort(arr[], low, high) { if (low < high) {
// pi is partitioning index, arr[pi] is now at right place pi = partition(arr, low, high); quickSort(arr, low, pi – 1); // Before pi quickSort(arr, pi + 1, high); // After pi } }
Pseudo code for partition() function
/* This function takes first element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than or equal to pivot) to left of pivot and all greater elements to right of pivot */
partition (arr[], low, high) { // first element as pivot pivot = arr[low] k = high for (i = high; i > low; i--) { if (arr[i] > pivot){ swap arr[i] and arr[k]; k--; } } swap arr[k] and arr[low] return k; }
Illustration of partition() :
Consider: arr[] = { 7, 6, 10, 5, 9, 2, 1, 15, 7 }
First Partition: low = 0, high = 8, pivot = arr[low] = 7 Initialize index of right most element k = high = 8.
Third partition: Here partition the segment {6, 5, 7}. The low = 2, high = 4, pivot = 6 and k = 4. If the same process is applied, we get correct position of 6 as index 3 and the left and the right part is having only one element.