QuickSort
Things to remember:
- Pivot
- Partitioning
- Recursion
- Concatenation
The following items are the key points to remember when implementing a quick sort algorithm.
The basic premise is that we are going to continue to recursively split or partition an array until we have sorted partitions at which point we will join them back together created our sorted array.
The Pivot
Our pivot value is the value in the array that we are comparing against to determine what goes into our 2 partitions...or our left and right partitions.
The simplest (but less efficient) form of a Quick Sort implementation is to use the first value in the Array. Other implementations choose a value in the middle of the Array and move outwards in both directions.
var arr = [100, 33, 2, 53, 4, 89, 9, 9];
var pivot = arr[0]; //simple
//OR
var pivot = arr.length / 2; //efficient
Partitions
Every time we split our array into two sections:
- Left - Values less than the pivot
- Right - Values greater than or equal to the pivot
We call these partitions, as they are "sections" of our original array.
var arr = [10, 3, 2, 53, 4, 89, 9, 9];
var pivot = arr[0]; //10
//After first split we have 2 partitions
var left = [3, 2, 4, 9, 9];
var right = [53, 89];
//NOTE: pivot is still 10 and not on left/right.
Recursion
Now that we have two partitions, we recursively pass them into the same function to continue to find our new pivot and left and right partitions.
var arr = [10, 3, 2, 34, 4, 53];
var pivot = arr[0]; //10
//After first split we have 2 partitions
var left = [3, 2, 4];
quickSort(left); //pivot = 3, left = [3, 2, 4], right = []
var right = [34, 53];
quickSort(right); //pivot = 34, left = [], right = [53]
NOTE: Our pivot is not added to our right partition but concatenated to the output of sorting the right partition.
Concatenation
On every iteration of our quicksort recursion we know that our pivot is greater than all values to the left and less than or equal to the first value on the right.
var arr = [10, 3, 2, 53, 34, 5];
left = [3, 2, 5], pivot = 10, right = [53, 34]
left = [2], pivot = 3, right = [5] left = [34], pivot = 53, right = []
left.concat(pivot, right); //[2,3,5] left.concat(pivot, right); //[34, 53]
[2, 3, 5].concat(pivot, [34, 53);
Therefore after our recursive function returns the sorted right partition, we simply concatenate the left partition, the pivot and the right partition.
QuickSort
By Jason Sewell
QuickSort
- 2,351