Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f25f9db

Browse files
Added sorting algorithms
1 parent 8975712 commit f25f9db

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

SortingAlgorithms/heapSort.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Testing Gist
2+
var heapSort = function(arr) {
3+
var n = arr.length;
4+
for(var i = Math.floor(n/2) - 1; i >= 0; i--)
5+
heapify(arr, n, i);
6+
7+
for(var i = n - 1; i >= 0; i--) {
8+
swap(arr, 0, i);
9+
heapify(arr, i, 0);
10+
}
11+
12+
return arr;
13+
}
14+
15+
var heapify = function(arr, n, i) {
16+
var left = 2 * i + 1;
17+
var right = 2 * i + 2;
18+
19+
if(left >= n && right >= n)
20+
return;
21+
22+
const leftValue = (left >= n) ? Number.NEGATIVE_INFINITY : arr[left];
23+
const rightValue = (right >= n) ? Number.NEGATIVE_INFINITY : arr[right];
24+
25+
if(arr[i] > leftValue && arr[i] > rightValue)
26+
return;
27+
28+
if(leftValue > rightValue) {
29+
swap(arr, i, left);
30+
heapify(arr, n, left);
31+
} else {
32+
swap(arr, i, right);
33+
heapify(arr, n, right);
34+
}
35+
}
36+
37+
var swap = function(arr, a, b) {
38+
var temp = arr[a];
39+
arr[a] = arr[b];
40+
arr[b] = temp;
41+
}
42+
43+
console.log(heapSort([14, 1, 10, 2, 3, 5, 6, 4, 7, 11, 12, 13]));
44+
console.log(heapSort([]));
45+
console.log(heapSort([1]));
46+
console.log(heapSort([2, 1]));
47+
console.log(heapSort([1,7,2,3,4,1,10,2,3,4,5]))
48+
49+
50+
51+

0 commit comments

Comments
 (0)