Skip to content

Commit 1ba8be9

Browse files
authored
Merge pull request vJechsmayr#44 from aprilxyc/quicksortbranch
completed quicksort by adding partition
2 parents ea62eef + a5f3a46 commit 1ba8be9

1 file changed

Lines changed: 35 additions & 3 deletions

File tree

‎SortingAlgorithms/quicksort.js‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,46 @@
11
//Language: Javascript
22
//Author: Viktoria Jechsmayr
33
//Github: https://github.com/vjechsmayr
4+
5+
// this swaps two items
6+
function swap(arr, left, right){
7+
let temp = arr[left];
8+
arr[left] = items[right];
9+
arr[right] = temp;
10+
}
11+
12+
// function to do partition added
13+
function partition(arr, left, right) {
14+
// get the pivot
15+
let pivot = arr[Math.floor((right + left) / 2)],
16+
// pointer to the left
17+
i = left,
18+
// pointer to the right
19+
j = right;
20+
while (i <= j) {
21+
while (arr[j] > pivot) {
22+
j--;
23+
}
24+
while (arr[i] < pivot) {
25+
i++;
26+
}
27+
if (i <= j) {
28+
// swap the 2 elements to get them in order
29+
swap(arr, i, j);
30+
i++;
31+
j--;
32+
}
33+
}
34+
return i;
35+
}
36+
437
function quickSort(arr, left, right){
5-
var len = arr.length,
38+
let len = arr.length,
639
pivot,
740
partitionIndex;
841

9-
1042
if(left < right){
11-
pivot = right;
43+
pivot = right;
1244
partitionIndex = partition(arr, pivot, left, right);
1345

1446
//sort left and right

0 commit comments

Comments
 (0)