-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort-JavaScript
More file actions
58 lines (49 loc) · 1.18 KB
/
Copy pathQuickSort-JavaScript
File metadata and controls
58 lines (49 loc) · 1.18 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
52
53
54
55
56
57
58
function partition(start, end, array){
let firstGreater = start;
let increment = start;
let pivotIndex = end;
let pivot = array[pivotIndex];
while(increment < pivotIndex){
if(array[increment] > pivot){
increment++;
}else{
swap(increment, firstGreater, array);
firstGreater++;
increment++;
}
}
swap(pivotIndex, firstGreater, array);
return firstGreater;
}
function swap(i,j,arr){
if(i==j){
return;
}
let ii = arr[i];
arr[i] = arr[j];
arr[j] = ii;
}
function shiftPivotToTheRight(start, end,array){
var pivot = start + Math.floor((end - start)/2);
swap(pivot, end, array);
}
function sortArray(start, end, array){
if(end - start <1){
return array;
}
shiftPivotToTheRight(start, end,array);
// debugger;
var pivot = partition(start, end, array);
;
sortArray(start, pivot - 1, array);
sortArray(pivot +1, end, array);
return array;
}
function quickSort( array) {
sortArray(0, array.length -1, array)
return array;
}
var res = quickSort([1,4,3,6,5,77,3]);
var res = quickSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
var res = quickSort( [1,4,2,1]);
console.log('res', res);