-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick-sort.js
More file actions
53 lines (42 loc) · 1006 Bytes
/
quick-sort.js
File metadata and controls
53 lines (42 loc) · 1006 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
41
42
43
44
45
46
47
48
49
50
51
52
53
'use strict';
let myArr = [44, 33, 22, 25, 35, 26, 35, 33, 12, 3, 4, 5, 7, 3, 6, 1];
console.log('beginning array:', myArr);
function swap(items, firstIndex, secondIndex) {
let temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
function partition(items, left, right) {
let pivot = items[Math.floor((right + left) / 2)];
let i = left;
let j = right;
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, left, right) {
let index;
if (items.length > 1) {
index = partition(items, left, right);
if (left < index - 1) {
quickSort(items, left, index - 1);
}
if (index < right) {
quickSort(items, index, right);
}
}
return items;
}
let result = quickSort(myArr, 0, myArr.length - 1);
console.log('sorted array:', result);