Skip to content

Commit f80a274

Browse files
Merge pull request ignacio-chiazzo#42 from Dhaxor/master
Update on Quick sort
2 parents c2bbdee + 0a7a956 commit f80a274

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

SortingAlgorithms/QuickSort.js

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

0 commit comments

Comments
 (0)