Skip to content

Instantly share code, notes, and snippets.

@Ananthusubramanian
Last active March 9, 2019 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ananthusubramanian/502738661993a405ae10fab99ceb8b31 to your computer and use it in GitHub Desktop.
Save Ananthusubramanian/502738661993a405ae10fab99ceb8b31 to your computer and use it in GitHub Desktop.
Algorithm 3
var array_length;
/* to create MAX array */
function heap_root(input, i) {
var left = 2 * i + 1;
var right = 2 * i + 2;
var max = i;
if (left < array_length && input[left] > input[max]) {
max = left;
}
if (right < array_length && input[right] > input[max]) {
max = right;
}
if (max != i) {
swap(input, i, max);
heap_root(input, max);
}
}
function swap(input, index_A, index_B) {
var temp = input[index_A];
input[index_A] = input[index_B];
input[index_B] = temp;
}
function heapSort(input) {
array_length = input.length;
for (var i = Math.floor(array_length / 2); i >= 0; i -= 1) {
heap_root(input, i);
}
for (i = input.length - 1; i > 0; i--) {
swap(input, 0, i);
array_length--;
heap_root(input, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment