Skip to content

Commit 1d676b1

Browse files
authored
Merge pull request #23 from Panzki/heapSort
Added heapsort algorithm.
2 parents 2c6d147 + 1a54138 commit 1d676b1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Sorts/heapSort.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Build a max heap out of the array. A heap is a specialized tree like
3+
* data structure that satisfies the heap property. The heap property
4+
* for max heap is the following: "if P is a parent node of C, then the
5+
* key (the value) of node P is greater than the key of node C"
6+
* Source: https://en.wikipedia.org/wiki/Heap_(data_structure)
7+
*/
8+
Array.prototype.heapify = function (index, heapSize) {
9+
10+
var largest = index;
11+
var leftIndex = 2 * index + 1;
12+
var rightIndex = 2 * index + 2;
13+
14+
if (leftIndex < heapSize && this[leftIndex] > this[largest]) {
15+
largest = leftIndex;
16+
}
17+
18+
if (rightIndex < heapSize && this[rightIndex] > this[largest]) {
19+
largest = rightIndex;
20+
}
21+
22+
if (largest !== index) {
23+
var temp = this[largest];
24+
this[largest] = this[index];
25+
this[index] = temp;
26+
27+
this.heapify(largest, heapSize);
28+
}
29+
};
30+
31+
/*
32+
* Heap sort sorts an array by building a heap from the array and
33+
* utilizing the heap property.
34+
* For more information see: https://en.wikipedia.org/wiki/Heapsort
35+
*/
36+
function heapSort(items) {
37+
38+
var length = items.length;
39+
40+
for (var i = Math.floor(items.length / 2) - 1; i > -1; i--) {
41+
items.heapify(i, length);
42+
}
43+
for (var j = length -1; j > 0; j--) {
44+
var tmp = items[0];
45+
items[0] = items[j];
46+
items[j] = tmp;
47+
items.heapify(0, j);
48+
}
49+
return items;
50+
}
51+
52+
//Implementation of heapSort
53+
54+
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
55+
//Array before Sort
56+
console.log(ar);
57+
heapSort(ar);
58+
//Array after sort
59+
console.log(ar);

0 commit comments

Comments
 (0)