|
1 | 1 | /**
|
2 | 2 | * @function QuickSort
|
3 | 3 | * @description Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy.
|
| 4 | + * It sorts the array in place by using a partitioning technique instead of creating separate arrays. |
4 | 5 | * @param {Integer[]} items - Array of integers
|
| 6 | + * @param {Integer} left - Starting index |
| 7 | + * @param {Integer} right - Ending index |
5 | 8 | * @return {Integer[]} - Sorted array.
|
6 | 9 | * @see [QuickSort](https://en.wikipedia.org/wiki/Quicksort)
|
7 | 10 | */
|
8 |
| -function quickSort(items) { |
9 |
| - const length = items.length |
10 |
| - |
11 |
| - if (length <= 1) { |
| 11 | +function quickSort(items, left = 0, right = items.length - 1) { |
| 12 | + if (left >= right) { |
12 | 13 | return items
|
13 | 14 | }
|
14 |
| - const PIVOT = items[0] |
15 |
| - const GREATER = [] |
16 |
| - const LESSER = [] |
17 |
| - |
18 |
| - for (let i = 1; i < length; i++) { |
19 |
| - if (items[i] > PIVOT) { |
20 |
| - GREATER.push(items[i]) |
21 |
| - } else { |
22 |
| - LESSER.push(items[i]) |
| 15 | + |
| 16 | + const pivotIndex = partition(items, left, right) |
| 17 | + quickSort(items, left, pivotIndex - 1) |
| 18 | + quickSort(items, pivotIndex + 1, right) |
| 19 | + |
| 20 | + return items |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * @function partition |
| 25 | + * @description Partitions the array in place and returns the index of the pivot. |
| 26 | + * @param {Integer[]} items - Array of integers |
| 27 | + * @param {Integer} left - Starting index |
| 28 | + * @param {Integer} right - Ending index |
| 29 | + * @return {Integer} - Pivot index. |
| 30 | + */ |
| 31 | +function partition(items, left, right) { |
| 32 | + const PIVOT = items[right] // Choose the rightmost element as pivot |
| 33 | + let partitionIndex = left |
| 34 | + |
| 35 | + for (let i = left; i < right; i++) { |
| 36 | + if (items[i] < PIVOT) { |
| 37 | + swap(items, i, partitionIndex) |
| 38 | + partitionIndex++ |
23 | 39 | }
|
24 | 40 | }
|
25 | 41 |
|
26 |
| - const sorted = [...quickSort(LESSER), PIVOT, ...quickSort(GREATER)] |
27 |
| - return sorted |
| 42 | + // Move the pivot to its correct position |
| 43 | + swap(items, partitionIndex, right) |
| 44 | + |
| 45 | + return partitionIndex |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * @function swap |
| 50 | + * @description Helper function to swap two elements in the array. |
| 51 | + * @param {Integer[]} items - Array of integers |
| 52 | + * @param {Integer} i - Index of the first element |
| 53 | + * @param {Integer} j - Index of the second element |
| 54 | + */ |
| 55 | +function swap(items, i, j) { |
| 56 | + const temp = items[i] |
| 57 | + items[i] = items[j] |
| 58 | + items[j] = temp |
28 | 59 | }
|
29 | 60 |
|
30 | 61 | export { quickSort }
|
0 commit comments