-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquick-sort.js
47 lines (41 loc) · 826 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
'use strict';
function quickSort(arr, left, right) {
let index;
if (arr.length > 1) {
index = partition(arr, left, right);
if (left < index - 1) {
quickSort(arr, left, index - 1);
}
if (right > index) {
quickSort(arr, index, right);
}
}
return arr;
}
function partition(arr, left, right) {
let pivot = arr[Math.floor((right + left) / 2)];
let i = left;
let j = right;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
swap(arr, i, j);
i++;
j--;
}
}
return i;
}
function swap(arr, left, right) {
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
let example = [8,4,23,42,16,15];
console.log(quickSort(example, 0, 5));
module.exports = quickSort;