Skip to content

Commit 43d2478

Browse files
committed
sorting
1 parent 0db8e90 commit 43d2478

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// O (n 2) worst case
2+
3+
function swap(a ,b) {
4+
const temp = a;
5+
a = b;
6+
b = temp;
7+
}
8+
9+
function partition(arr, first, last) {
10+
const pivot = first;
11+
let lowerIndex = first + 1;
12+
let upperIndex = last;
13+
// call first element as pivot
14+
// loop till the higher and lower indices cross each other
15+
while (upperIndex >= lowerIndex) {
16+
if (arr[pivot] > arr[lowerIndex]) {
17+
lowerIndex++;
18+
} else if (arr[upperIndex] > arr[pivot]) {
19+
upperIndex--;
20+
} else if (arr[pivot] > arr[upperIndex] && arr[lowerIndex] > arr[upperIndex]) {
21+
// now lower index value is greater than pivot so we stop incrementing the lowerindex
22+
// we will decrement the upperIndex until we find a value that is less than pivot and lowerindex value we will switch array indices positions
23+
const temp = arr[upperIndex];
24+
arr[upperIndex] = arr[lowerIndex];
25+
arr[lowerIndex] = temp;
26+
upperIndex--;
27+
lowerIndex++;
28+
}
29+
}
30+
// swap pivot with uper
31+
const temp = arr[upperIndex];
32+
arr[upperIndex] = arr[pivot];
33+
arr[pivot] = temp;
34+
return upperIndex;
35+
}
36+
37+
function quickSort(arr, first, last) {
38+
if (first < last) {
39+
const pivot = partition(arr, first, last);
40+
quickSort(arr, first, pivot - 1);
41+
quickSort(arr, pivot + 1, last);
42+
}
43+
}
44+
45+
46+
const arr = [20, 6, 8, 53, 23, 87, 42, 19];
47+
console.log(arr, 'orignal');
48+
quickSort(arr, 0, (arr.length - 1));
49+
console.log(arr, 'sorted');
50+
51+
module.exports = quickSort;

0 commit comments

Comments
 (0)