-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick_sort.js
50 lines (37 loc) · 994 Bytes
/
quick_sort.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
const arr = [5, 2, 1, 4, 3];
const swap = (arr, left, right) => {
const swapValue = arr[left];
arr[left] = arr[right];
arr[right] = swapValue;
}
const partition = (arr, left, right) => {
const pivot = arr[Math.floor((left + right) / 2)];
let pointLeft = left;
let pointRight = right;
while (pointLeft <= pointRight) {
while(arr[pointLeft] < pivot) {
pointLeft++;
}
while(arr[pointRight] > pivot) {
pointRight--;
}
swap(arr, pointLeft, pointRight);
pointLeft++;
pointRight--;
}
return pointLeft;
}
const quickSort = (arr, left, right) => {
if (arr <= 1) {
return arr;
}
const index = partition(arr, left, right);
if (index -1 > left) {
quickSort(arr, left, index - 1);
}
if (index < right) {
quickSort(arr, index, right);
}
return arr;
}
console.log(quickSort(arr, 0, arr.length - 1).join().replace(",", " "));