Skip to content

Commit 91f4604

Browse files
committed
sort algorithm added
1 parent bab19ad commit 91f4604

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

quick_sort.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
function quickSort(arr, left, right) {
2+
let len = arr.length,
3+
pivot,
4+
partitionIndex;
5+
6+
7+
if (left < right) {
8+
pivot = right;
9+
partitionIndex = partition(arr, pivot, left, right);
10+
11+
//sort left and right
12+
quickSort(arr, left, partitionIndex - 1);
13+
quickSort(arr, partitionIndex + 1, right);
14+
}
15+
return arr;
16+
}
17+
function partition(arr, pivot, left, right) {
18+
let pivotValue = arr[pivot],
19+
partitionIndex = left;
20+
21+
for (let i = left; i < right; i++) {
22+
if (arr[i] < pivotValue) {
23+
swap(arr, i, partitionIndex);
24+
partitionIndex++;
25+
}
26+
}
27+
swap(arr, right, partitionIndex);
28+
return partitionIndex;
29+
}
30+
function swap(arr, i, j) {
31+
let temp = arr[i];
32+
arr[i] = arr[j];
33+
arr[j] = temp;
34+
}
35+
36+
// console.log(quickSort([7, 5, 2, 4, 3, 9]));
37+
// console.log(quickSort([9, 7, 5, 4, 3, 1]));
38+
// console.log(quickSort([1, 2, 3, 4, 5, 6]));

0 commit comments

Comments
 (0)