-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathQuickSort.js
More file actions
28 lines (23 loc) · 773 Bytes
/
QuickSort.js
File metadata and controls
28 lines (23 loc) · 773 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* @function quickSort
* @description Quick Sort is a divide-and-conquer comparison-based sorting algorithm.
* @param {number[]} items - Array of integers
* @returns {number[]} - Sorted array
* @timecomplexity Average: O(n log n), Worst: O(n²)
* @spacecomplexity O(n)
* @see https://en.wikipedia.org/wiki/Quicksort
*/
function quickSort(items) {
if (items.length <= 1) return items
const pivotIndex = Math.floor(items.length / 2)
const pivot = items[pivotIndex]
const lesser = []
const greater = []
for (let i = 0; i < items.length; i++) {
if (i === pivotIndex) continue
if (items[i] < pivot) lesser.push(items[i])
else greater.push(items[i])
}
return [...quickSort(lesser), pivot, ...quickSort(greater)]
}
export { quickSort }