-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgQuickSort.js
44 lines (38 loc) · 1016 Bytes
/
algQuickSort.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
Array.prototype.quickSort = function(left, right) {
var swap = function(collection, first, second) {
var helper = collection[first];
collection[first] = collection[second];
collection[second] = helper;
};
var partition = function(collection, left, right) {
var pivot = collection[Math.floor((left + right) / 2)];
while (left <= right) {
while (collection[left] < pivot) {
left++;
}
while (collection[right] > pivot) {
right--;
}
if (left <= right) {
swap(collection, left, right);
left++;
right--;
}
}
return left;
};
var index;
if (this.length > 1) {
left = typeof left != "number" ? 0 : left;
right = typeof right != "number" ? this.length - 1 : right;
index = partition(this, left, right);
}
if (left < index - 1) {
this.quickSort(left, index - 1);
}
if (right > index) {
this.quickSort(index, right);
}
return this;
};
var testArray = [5, 3, 4, 6, 7, 10];