-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathQuickSort.js
61 lines (53 loc) · 1.71 KB
/
QuickSort.js
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @function QuickSort
* @description Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy.
* It sorts the array in place by using a partitioning technique instead of creating separate arrays.
* @param {Integer[]} items - Array of integers
* @param {Integer} left - Starting index
* @param {Integer} right - Ending index
* @return {Integer[]} - Sorted array.
* @see [QuickSort](https://en.wikipedia.org/wiki/Quicksort)
*/
function quickSort(items, left = 0, right = items.length - 1) {
if (left >= right) {
return items
}
const pivotIndex = partition(items, left, right)
quickSort(items, left, pivotIndex - 1)
quickSort(items, pivotIndex + 1, right)
return items
}
/**
* @function partition
* @description Partitions the array in place and returns the index of the pivot.
* @param {Integer[]} items - Array of integers
* @param {Integer} left - Starting index
* @param {Integer} right - Ending index
* @return {Integer} - Pivot index.
*/
function partition(items, left, right) {
const PIVOT = items[right] // Choose the rightmost element as pivot
let partitionIndex = left
for (let i = left; i < right; i++) {
if (items[i] < PIVOT) {
swap(items, i, partitionIndex)
partitionIndex++
}
}
// Move the pivot to its correct position
swap(items, partitionIndex, right)
return partitionIndex
}
/**
* @function swap
* @description Helper function to swap two elements in the array.
* @param {Integer[]} items - Array of integers
* @param {Integer} i - Index of the first element
* @param {Integer} j - Index of the second element
*/
function swap(items, i, j) {
const temp = items[i]
items[i] = items[j]
items[j] = temp
}
export { quickSort }