|
1 | 1 | /** |
2 | | - * @function QuickSort |
3 | | - * @description Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy. |
4 | | - * @param {Integer[]} items - Array of integers |
5 | | - * @return {Integer[]} - Sorted array. |
6 | | - * @see [QuickSort](https://en.wikipedia.org/wiki/Quicksort) |
| 2 | + * @function quickSort |
| 3 | + * @description Quick Sort is a divide-and-conquer comparison-based sorting algorithm. |
| 4 | + * @param {number[]} items - Array of integers |
| 5 | + * @returns {number[]} - Sorted array |
| 6 | + * @timecomplexity Average: O(n log n), Worst: O(n²) |
| 7 | + * @spacecomplexity O(n) |
| 8 | + * @see https://en.wikipedia.org/wiki/Quicksort |
7 | 9 | */ |
8 | 10 | function quickSort(items) { |
9 | | - const length = items.length |
| 11 | + if (items.length <= 1) return items |
10 | 12 |
|
11 | | - if (length <= 1) { |
12 | | - return items |
13 | | - } |
14 | | - const PIVOT = items[0] |
15 | | - const GREATER = [] |
16 | | - const LESSER = [] |
| 13 | + const pivotIndex = Math.floor(items.length / 2) |
| 14 | + const pivot = items[pivotIndex] |
| 15 | + |
| 16 | + const lesser = [] |
| 17 | + const greater = [] |
17 | 18 |
|
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]) |
23 | | - } |
| 19 | + for (let i = 0; i < items.length; i++) { |
| 20 | + if (i === pivotIndex) continue |
| 21 | + if (items[i] < pivot) lesser.push(items[i]) |
| 22 | + else greater.push(items[i]) |
24 | 23 | } |
25 | 24 |
|
26 | | - const sorted = [...quickSort(LESSER), PIVOT, ...quickSort(GREATER)] |
27 | | - return sorted |
| 25 | + return [...quickSort(lesser), pivot, ...quickSort(greater)] |
28 | 26 | } |
29 | 27 |
|
30 | 28 | export { quickSort } |
0 commit comments