Skip to content

Commit 3e35008

Browse files
authored
Merge pull request argonautica#41 from thakurutkarsh22/master
AddingQuickSort
2 parents c0eb41a + be60d9d commit 3e35008

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

Javascript/HeapSort.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
function heapSort(arr){
2+
var len = arr.length,
3+
end = len-1;
4+
5+
heapify(arr, len);
6+
7+
while(end > 0){
8+
swap(arr, end--, 0);
9+
DownHeapify(arr, 0, end);
10+
}
11+
return arr;
12+
}
13+
14+
function heapify(arr, len){
15+
// breaking the array into root + two sides, to create tree (heap)
16+
var mid = Math.floor((len-2)/2);
17+
while(mid >= 0){
18+
DownHeapify(arr, mid--, len-1);
19+
}
20+
}
21+
22+
function DownHeapify(arr, start, end){
23+
var root = start,
24+
child = root*2 + 1,
25+
toSwap = root;
26+
while(child <= end){
27+
if(arr[toSwap] < arr[child]){
28+
swap(arr, toSwap, child);
29+
}
30+
if(child+1 <= end && arr[toSwap] < arr[child+1]){
31+
swap(arr, toSwap, child+1)
32+
}
33+
if(toSwap != root){
34+
swap(arr, root, toSwap);
35+
root = toSwap;
36+
}
37+
else{
38+
return;
39+
}
40+
toSwap = root;
41+
child = root*2+1
42+
}
43+
}
44+
45+
46+
function swap(arr, i, j){
47+
var temp = arr[i];
48+
arr[i] = arr[j];
49+
arr[j] = temp;
50+
}

Javascript/Quicksort.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
function quickSort(arr, left, right){
2+
var 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+
18+
function partition(arr, pivot, left, right){
19+
var pivotValue = arr[pivot],
20+
partitionIndex = left;
21+
22+
for(var i = left; i < right; i++){
23+
if(arr[i] < pivotValue){
24+
swap(arr, i, partitionIndex);
25+
partitionIndex++;
26+
}
27+
}
28+
swap(arr, right, partitionIndex);
29+
return partitionIndex;
30+
}
31+
32+
function swap(arr, i, j){
33+
var temp = arr[i];
34+
arr[i] = arr[j];
35+
arr[j] = temp;
36+
}
37+

0 commit comments

Comments
 (0)