-
Notifications
You must be signed in to change notification settings - Fork 497
/
Copy pathquicksort.js
84 lines (72 loc) · 2.11 KB
/
quicksort.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// array to sort
let array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
// basic implementation (pivot is the first element of the array)
function quicksortBasic(array) {
if(array.length < 2) {
return array;
}
let pivot = array[0];
let lesser = [];
let greater = [];
for(let i = 1; i < array.length; i++) {
if(array[i] < pivot) {
lesser.push(array[i]);
} else {
greater.push(array[i]);
}
}
return quicksortBasic(lesser).concat(pivot, quicksortBasic(greater));
}
console.log(quicksortBasic(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
// swap function helper
function swap(array, i, j) {
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// classic implementation (with Hoare or Lomuto partition scheme, you can comment either one method or the other to see the difference)
function quicksort(array, left, right) {
left = left || 0;
right = right || array.length - 1;
// var pivot = partitionLomuto(array, left, right); // you can play with both partition
let pivot = partitionHoare(array, left, right); // you can play with both partition
if(left < pivot - 1) {
quicksort(array, left, pivot - 1);
}
if(right > pivot) {
quicksort(array, pivot, right);
}
return array;
}
// Lomuto partition scheme, it is less efficient than the Hoare partition scheme
function partitionLomuto(array, left, right) {
let pivot = right;
let i = left;
for(let j = left; j < right; j++) {
if(array[j] <= array[pivot]) {
swap(array, i, j);
i = i + 1;
}
}
swap(array, i, j);
return i;
}
// Hoare partition scheme, it is more efficient than the Lomuto partition scheme because it does three times fewer swaps on average
function partitionHoare(array, left, right) {
let pivot = Math.floor((left + right) / 2 );
while(left <= right) {
while(array[left] < array[pivot]) {
left++;
}
while(array[right] > array[pivot]) {
right--;
}
if(left <= right) {
swap(array, left, right);
left++;
right--;
}
}
return left;
}
console.log(quicksort(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]