-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort.js
More file actions
37 lines (35 loc) · 1.14 KB
/
quickSort.js
File metadata and controls
37 lines (35 loc) · 1.14 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
// fn to calc the length of a list of items
function count(iterable){
if(!isNaN(iterable)) iterable = `${iterable}`;
let i = 0;
for(const item of iterable) i++;
return i;
}
// quick sort Algorithm (it's a recursive one) On 28th August 2024 [ 10:47 PM ]
function quickSort(list=[], start =0 ,end= count(list) - 1){
if(start < end){
let pivotIndex = partition(list, start, end);
quickSort(list, start, pivotIndex-1);
quickSort(list, pivotIndex+1, end);
}
return list;
}
function partition(list, start, end){
let pivot = list[end], i = start -1;
for(let k = start; k<end; k++){
if(list[k] < pivot){
i++;
[list[i], list[k]] = [list[k], list[i]];
}
}
[list[i+1], list[end]] = [list[end],list[i+1]];
return i+1;
}
/**
* Testing the Algo with a normal unordered, ordered, reverse ordered lists
* and a list with only one misplaced element
*/
console.log(quickSort([1,3,2,4,4,5,6,7,8,9]));
console.log(quickSort([13,12,11,9,8,7,6,5,3,2]));
console.log(quickSort([10,11,22,33,44,55,66,77,88,99]));
console.log(quickSort([22,3,44,5,6,8,7,10,9,15]));