-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathquickSort.js
66 lines (49 loc) · 1.69 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
const numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0];
function quickSort(array, left, right) {
const len = array.length;
let pivot;
let partitionIndex;
if (left < right) {
pivot = right;
partitionIndex = partition(array, pivot, left, right);
// Sort left and right
quickSort(array, left, partitionIndex - 1);
quickSort(array, partitionIndex + 1, right);
}
return array;
}
function partition(array, pivot, left, right) {
let pivotValue = array[pivot];
let partitionIndex = left;
for (let i = left; i < right; i++) {
if (array[i] < pivotValue) {
swap(array, i, partitionIndex);
partitionIndex++;
}
}
swap(array, right, partitionIndex);
return partitionIndex;
}
function swap(array, firstIndex, secondIndex) {
let temp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
}
function quickSortMine(array, left, right) {
if (array.length <= 1) {
return array;
}
let indexCounter = 0;
for (let i = 0; i < array.length; i++) {
if (array[i - indexCounter] > array[right - indexCounter]) {
array.push(array.splice(i - indexCounter, 1)[0]);
indexCounter++;
}
}
let leftArray = array.slice(left, right - indexCounter);
let rightArray = array.slice(right - indexCounter + 1, array.length);
return quickSort(leftArray, 0, leftArray.length - 1).concat(array[right - indexCounter]).concat(quickSort(rightArray, 0, rightArray.length - 1));
}
//Select first and last index as 2nd and 3rd parameters
const answer = quickSort(numbers, 0, numbers.length - 1);
console.log(answer);