|
| 1 | +// O (n 2) worst case |
| 2 | + |
| 3 | +function partition(arr, first, last) { |
| 4 | + const pivot = first; |
| 5 | + let lowerIndex = first + 1; |
| 6 | + let upperIndex = last; |
| 7 | + // call first element as pivot |
| 8 | + // loop till the higher and lower indices cross each other |
| 9 | + while (upperIndex >= lowerIndex) { |
| 10 | + if (arr[pivot] > arr[lowerIndex]) { |
| 11 | + lowerIndex++; |
| 12 | + } else if (arr[upperIndex] > arr[pivot]) { |
| 13 | + upperIndex--; |
| 14 | + } else if (arr[pivot] > arr[upperIndex] && arr[lowerIndex] > arr[upperIndex]) { |
| 15 | + // now lower index value is greater than pivot so we stop incrementing the lowerindex |
| 16 | + // we will decrement the upperIndex until we find a value that is less than pivot and lowerindex value we will switch array indices positions |
| 17 | + const temp = arr[upperIndex]; |
| 18 | + arr[upperIndex] = arr[lowerIndex]; |
| 19 | + arr[lowerIndex] = temp; |
| 20 | + upperIndex--; |
| 21 | + lowerIndex++; |
| 22 | + } |
| 23 | + } |
| 24 | + // swap pivot with uper |
| 25 | + const temp = arr[upperIndex]; |
| 26 | + arr[upperIndex] = arr[pivot]; |
| 27 | + arr[pivot] = temp; |
| 28 | + return upperIndex; |
| 29 | +} |
| 30 | + |
| 31 | +function quickSort(arr, first, last) { |
| 32 | + if (first < last) { |
| 33 | + const pivot = partition(arr, first, last); |
| 34 | + quickSort(arr, first, pivot - 1); |
| 35 | + quickSort(arr, pivot + 1, last); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +const arr = [20, 6, 8, 53, 23, 87, 42, 19]; |
| 41 | +console.log(arr, 'orignal'); |
| 42 | +quickSort(arr, 0, (arr.length - 1)); |
| 43 | +console.log(arr, 'sorted'); |
| 44 | + |
| 45 | +module.exports = quickSort; |
0 commit comments