Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit ba924ec

Browse files
authored
Add quick sort algorithm in JavaScript (#909)
1 parent 38ac557 commit ba924ec

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Javascript/Algorithms/quick-sort.js

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
var items = [5,3,7,6,2,9];
2+
function swap(items, leftIndex, rightIndex){
3+
var temp = items[leftIndex];
4+
items[leftIndex] = items[rightIndex];
5+
items[rightIndex] = temp;
6+
}
7+
function partition(items, left, right) {
8+
var pivot = items[Math.floor((right + left) / 2)], //middle element
9+
i = left, //left pointer
10+
j = right; //right pointer
11+
while (i <= j) {
12+
while (items[i] < pivot) {
13+
i++;
14+
}
15+
while (items[j] > pivot) {
16+
j--;
17+
}
18+
if (i <= j) {
19+
swap(items, i, j); //sawpping two elements
20+
i++;
21+
j--;
22+
}
23+
}
24+
return i;
25+
}
26+
27+
function quickSort(items, left, right) {
28+
var index;
29+
if (items.length > 1) {
30+
index = partition(items, left, right); //index returned from partition
31+
if (left < index - 1) { //more elements on the left side of the pivot
32+
quickSort(items, left, index - 1);
33+
}
34+
if (index < right) { //more elements on the right side of the pivot
35+
quickSort(items, index, right);
36+
}
37+
}
38+
return items;
39+
}
40+
// first call to quick sort
41+
var sortedArray = quickSort(items, 0, items.length - 1);
42+
console.log(sortedArray); //prints [2,3,5,6,7,9]

0 commit comments

Comments
 (0)