// 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
}
}
/* 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;
}
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.
- Traverse from i = high to low:
- if arr[i] is greater than pivot:
- Swap arr[i] and arr[k].
- Decrement k;
- At the end swap arr[low] and arr[k].
Now the correct position of pivot is index 5
First partitionSecond Partition: low = 0, high = 4, pivot = arr[low] = 2
Similarly initialize k = high = 4;
The correct position of 2 becomes index 1. And the left part is only one element and the right part has {6, 5, 7}.
Partition of the left halfOn the other hand partition happens on the segment [6, 8] i.e., the array {10, 9, 15}.
Here low = 6, high = 8, pivot = 10 and k = 8.
The correct position of 10 becomes index 7 and the right and left part both has only one element.
Partition of the right halfThird 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.
Third partitionThe total array becomes sorted in this way. Check the below image for the recursion tree
Recursion tree for partitions