R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
{quicksort}
The Question
Use the quicksort algorithm to sort an array of integers.
What is quicksort?
- Quicksort uses a pivot number and then compares the rest of the array values to the pivot number
- If the array value is less than the pivot number, it goes to the left of the pivot number
- If the array value is greater than the pivot number, it goes to the right of the pivot number
- This procedure is then repeated on the numbers to the left and the numbers to the right
- The two base cases are when there is only one number to the left and only one number to the right
Video demonstration of quicksort
- Note, that in this video the pivot is always taken as the first number to the left. This is not recommended as it can lead to the worst case scenario O(n^2)
'use strict'
function quickSort(arr){
(function qS(leftPointer, rightPointer, pivotIndex){
for(let i = rightPointer; i > leftPointer; i--){
if(arr[i]<arr[pivotIndex] && i>pivotIndex || arr[i]>arr[pivotIndex] && i<pivotIndex){
let tmp = arr[pivotIndex];
arr[pivotIndex] = arr[i];
arr[i] = tmp;
pivotIndex = i;
}
}
//note, using a random pivot point to prevent worst-case behavior
if(pivotIndex > leftPointer){
let ranPiv = Math.floor(Math.random()*(pivotIndex - leftPointer));
qS(0, pivotIndex, ranPiv);
}
if(pivotIndex < rightPointer){
let ranPiv = Math.floor(Math.random()*(rightPointer - pivotIndex))+pivotIndex+1;
qS(pivotIndex+1, rightPointer, ranPiv);
}
})(0, arr.length - 1, Math.floor(Math.random()*arr.length));
return arr;
}
var arr = [5,2,4,1,3,7,9,8];
quickSort(arr); //returns [1,2,3,4,5,6,7,8,9]
Solution
Take aways
- Quicksort time complexity:
- Best Case= O(nlogn)
- Average Case = O(nlogn)
- Worst Case = O(n^2)
- Quicksort space complexity: O(logn) on average
- Worst time case can be avoided depending on the selection of the pivot point. Picking randomly is a good strategy, picking the median number is the best strategy
- Quicksort is often preferred to Mergesort. Despite the fact they are both O(logn), Quicksort is often faster in practice due to cache locality and it requires little extra storage
Solution
Copy of Quicksort
By Tom Kelly
Copy of Quicksort
Technical interview problem to implement the quicksort algorithm
- 1,232