-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.js
More file actions
40 lines (35 loc) · 1017 Bytes
/
quickSort.js
File metadata and controls
40 lines (35 loc) · 1017 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
29
30
31
32
33
34
35
36
37
38
39
40
const items = [5,8,1,3,7,9,2];
function swap(items, leftIndex, rightIndex) {
const temp = items[leftIndex];
items[leftIndex] = items[rightIndex];
items[rightIndex] = temp;
}
function partition(items, leftIndex, rightIndex) {
const pivot = items[Math.floor((rightIndex + leftIndex) / 2)];
let i = leftIndex, j = rightIndex;
while (i <= j) {
while (items[i] < pivot) i++;
while (items[j] > pivot) j--;
if (i <= j) {
swap(items, i, j);
i++;
j--;
}
}
return i;
}
function quickSort(items, leftIndex, rightIndex) {
let index;
if (items.length > 1) {
index = partition(items, leftIndex, rightIndex);
if (leftIndex < index - 1) {
quickSort(items, leftIndex, index - 1);
}
if (index < rightIndex) {
quickSort(items, index, rightIndex);
}
}
return items;
}
const sortedArray = quickSort(items, 0, items.length - 1);
console.log(sortedArray);