|
1 |
| -const swap = (arr, i, j) => { |
2 |
| - const temp = arr[i]; |
3 |
| - arr[i] = arr[j]; |
4 |
| - arr[j] = temp; |
5 |
| -}; |
6 |
| - |
7 |
| -const partition = (array, left, right) => { |
8 |
| - const pivot = array[Math.floor((right + left) / 2)]; |
9 |
| - let i = left; |
10 |
| - let j = right; |
11 |
| - while (i <= j) { |
12 |
| - while (array[i] < pivot) { |
13 |
| - i++; |
14 |
| - } |
15 |
| - while (array[j] > pivot) { |
16 |
| - j--; |
17 |
| - } |
18 |
| - if (i <= j) { |
19 |
| - swap(array, i, j); |
20 |
| - i++; |
21 |
| - j--; |
22 |
| - } |
| 1 | +const QuickSort = (array) => { |
| 2 | + if (array.length <= 1) { |
| 3 | + return array; |
23 | 4 | }
|
24 |
| - return i; |
25 |
| -}; |
26 | 5 |
|
27 |
| -const sort = (array, left, right) => { |
28 |
| - if (array.length > 1) { |
29 |
| - const index = partition(array, left, right); |
30 |
| - if (left < index - 1) { |
31 |
| - sort(array, left, index - 1); |
32 |
| - } |
33 |
| - if (index < right) { |
34 |
| - sort(array, index, right); |
| 6 | + const leftArray = []; |
| 7 | + const rightArray = []; |
| 8 | + |
| 9 | + const pivotElement = array.shift(); |
| 10 | + const centerArray = [pivotElement]; |
| 11 | + |
| 12 | + while (array.length) { |
| 13 | + const currentElement = array.shift(); |
| 14 | + if (currentElement === pivotElement) { |
| 15 | + centerArray.push(currentElement); |
| 16 | + } else if (currentElement < pivotElement) { |
| 17 | + leftArray.push(currentElement); |
| 18 | + } else { |
| 19 | + rightArray.push(currentElement); |
35 | 20 | }
|
36 | 21 | }
|
37 |
| - return array; |
| 22 | + |
| 23 | + const leftArraySorted = QuickSort(leftArray); |
| 24 | + const rightArraySorted = QuickSort(rightArray); |
| 25 | + |
| 26 | + return leftArraySorted.concat(centerArray, rightArraySorted); |
38 | 27 | };
|
39 | 28 |
|
40 |
| -module.exports = sort; |
| 29 | +module.exports = QuickSort; |
0 commit comments