forked from vJechsmayr/JavaScriptAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.js
More file actions
51 lines (46 loc) · 1.08 KB
/
Copy pathquicksort.js
File metadata and controls
51 lines (46 loc) · 1.08 KB
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
//Language: Javascript
//Author: Viktoria Jechsmayr
//Github: https://github.com/vjechsmayr
// this swaps two items
function swap(arr, left, right){
let temp = arr[left];
arr[left] = items[right];
arr[right] = temp;
}
// function to do partition added
function partition(arr, left, right) {
// get the pivot
let pivot = arr[Math.floor((right + left) / 2)],
// pointer to the left
i = left,
// pointer to the right
j = right;
while (i <= j) {
while (arr[j] > pivot) {
j--;
}
while (arr[i] < pivot) {
i++;
}
if (i <= j) {
// swap the 2 elements to get them in order
swap(arr, i, j);
i++;
j--;
}
}
return i;
}
function quickSort(arr, left, right){
let len = arr.length,
pivot,
partitionIndex;
if(left < right){
pivot = right;
partitionIndex = partition(arr, pivot, left, right);
//sort left and right
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
return arr;
}