(nums)
| 13 | */ |
| 14 | |
| 15 | function quickSort(nums) { |
| 16 | // base case, arrays of length 0 or 1 are sorted already |
| 17 | if (nums.length <= 1) return nums; |
| 18 | |
| 19 | // last number is the pivot |
| 20 | const pivot = nums[nums.length - 1]; |
| 21 | const left = []; |
| 22 | const right = []; |
| 23 | |
| 24 | // sort all smaller numbers than the pivot into left |
| 25 | // and all bigger numbers into right |
| 26 | for (let i = 0; i < nums.length - 1; i++) { |
| 27 | if (nums[i] < pivot) { |
| 28 | left.push(nums[i]); |
| 29 | } else { |
| 30 | right.push(nums[i]); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | // call quick sort on left and right |
| 35 | // concat all into one big array with pivot in the middle |
| 36 | return [...quickSort(left), pivot, ...quickSort(right)]; |
| 37 | // the below is equivalent |
| 38 | // return quickSort(left).concat(pivot, quickSort(right)) |
| 39 | } |
| 40 | |
| 41 | // unit tests |
| 42 | // do not modify the below code |
no test coverage detected