Skip to content

Commit da50af3

Browse files
Add Quick Sort implementation in JavaScript
1 parent a52354a commit da50af3

File tree

1 file changed

+18
-20
lines changed

1 file changed

+18
-20
lines changed

Sorts/QuickSort.js

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,28 @@
11
/**
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
79
*/
810
function quickSort(items) {
9-
const length = items.length
11+
if (items.length <= 1) return items
1012

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 = []
1718

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])
2423
}
2524

26-
const sorted = [...quickSort(LESSER), PIVOT, ...quickSort(GREATER)]
27-
return sorted
25+
return [...quickSort(lesser), pivot, ...quickSort(greater)]
2826
}
2927

3028
export { quickSort }

0 commit comments

Comments
 (0)