File tree Expand file tree Collapse file tree 1 file changed +17
-0
lines changed Expand file tree Collapse file tree 1 file changed +17
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Note : This is not a in place quick sort; but example gives a good intuition about the algorithm
2
+ // Credits : https://itnext.io/a-sort-of-quick-guide-to-quicksort-and-hoares-partitioning-scheme-in-javascript-7792112c6d1
3
+ const quickSort = ( arr ) => {
4
+ // base case; An array with less than 2 elements is always sorted
5
+ if ( arr . length <= 1 ) return arr ;
6
+ // Choose a random pivot
7
+ const pivot = arr . splice ( Math . floor ( Math . random ( ) * ( arr . length - 1 ) ) , 1 ) ;
8
+ const left = [ ] ;
9
+ const right = [ ] ;
10
+ // left has all the elements lesser than pivot; right has elements greater than pivot
11
+ arr . forEach ( el => el < pivot ? left . push ( el ) : right . push ( el ) ) ;
12
+ // recursively call on the left and right arrays
13
+ const sortedLeft = quickSort ( left ) ;
14
+ const sortedRight = quickSort ( right ) ;
15
+ // now combine the sortedLeft, pivot(remember it is sandwiched between left and right), sortedRight
16
+ return [ ...sortedLeft , ...pivot , ...sortedRight ] ;
17
+ }
You can’t perform that action at this time.
0 commit comments