-
Notifications
You must be signed in to change notification settings - Fork 0
/
tempCodeRunnerFile.js
56 lines (53 loc) · 1.43 KB
/
tempCodeRunnerFile.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
const swap = (arr, i, j) => {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
const partition = (arr, left, right, pivot) => {
let value = arr[pivot];
let i = left;
for (let j = left; j < right; j++) {
if (arr[j] < value) {
swap(arr, i, j);
i++;
}
}
swap(arr, i, pivot);
return i;
}
// const partition = (arr, pivot, left, right) => {
// const pivotVal = arr[pivot]
// let startIndex = left
// for (let i = left; i < right; i++) {
// if (arr[i] < pivotVal) {
// swap(arr, i, startIndex)
// startIndex++
// }
// }
// swap(arr, startIndex, pivot)
// return startIndex
// }
const quickSort = (arr, left, right) => {
// if (left >= right) return;
// let pivot = right;
// let i = partition(arr, left, right, pivot);
// console.log(i)
// quickSort(arr, left, i - 1 > left ? i - 1 : left);
// quickSort(arr, right, i + 1 < right ? i + 1 : right);
if (left < right) {
let pivot = right
let partitionIndex = partition(arr, left, right, pivot)
console.log(partitionIndex)
quickSort(arr, left, partitionIndex - 1 < left ? left : partitionIndex - 1)
quickSort(arr, partitionIndex + 1 > right ? right : partitionIndex + 1, right)
}
}
const testArr = []
let i = 0
while (i < 10) {
testArr.push(Math.floor(Math.random() * 1000));
i++;
}
console.log('sort before...', testArr)
quickSort(testArr, 0, testArr.length - 1);
console.log('sort after....', testArr);