Skip to content

Instantly share code, notes, and snippets.

@piyusharora1989
Created November 21, 2018 16:24
Show Gist options
  • Save piyusharora1989/dbcdd556a4f81a23a5ef0334088ed3c0 to your computer and use it in GitHub Desktop.
Save piyusharora1989/dbcdd556a4f81a23a5ef0334088ed3c0 to your computer and use it in GitHub Desktop.
function sort(arr) {
let last_index = arr.length - 1;
while (last_index > 0) {
heapify(arr, last_index);
swap(0, last_index, arr);
last_index--;
}
return arr;
}
function heapify(arr, last_index) {
let start_point = Math.floor((last_index - 1) / 2);
for (let i = start_point; i >= 0; i--) {
let min = i;
if (arr[2 * i + 1] < arr[i]) {
min = 2 * i + 1;
}
if (last_index >= 2 * i + 2) {
if (arr[2 * i + 2] < arr[min]) {
min = 2 * i + 2;
}
}
swap(i, min, arr);
}
}
function swap(i, min, arr) {
if (i == min) {
return;
} else {
arr[min] = arr[min] + arr[i];
arr[i] = arr[min] - arr[i];
arr[min] = arr[min] - arr[i];
}
}
v = sort([27, 32, 1, 7, 9, 99, 99, 25, 1, 30, 1]);
console.log(v);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment