Skip to content

Commit 40a9414

Browse files
committed
feat: improve space complexity of QuickSort algorithm
1 parent 9010481 commit 40a9414

File tree

1 file changed

+46
-15
lines changed

1 file changed

+46
-15
lines changed

Sorts/QuickSort.js

+46-15
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,61 @@
11
/**
22
* @function QuickSort
33
* @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.
45
* @param {Integer[]} items - Array of integers
6+
* @param {Integer} left - Starting index
7+
* @param {Integer} right - Ending index
58
* @return {Integer[]} - Sorted array.
69
* @see [QuickSort](https://en.wikipedia.org/wiki/Quicksort)
710
*/
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) {
1213
return items
1314
}
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++
2339
}
2440
}
2541

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
2859
}
2960

3061
export { quickSort }

0 commit comments

Comments
 (0)