Heapsort js code example
Example 1: heap sort javascript
var array_length;
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);
}
}
var arr = [3, 0, 2, 5, -1, 4, 1];
heapSort(arr);
console.log(arr);
Example 2: heapsort
Implementation of heap sort in C++:
#include <bits/stdc++.h>
using namespace std;
void heapify(int A[], int n, int i)
{
int largest = i;
int left_child = 2 * i + 1;
int right_child = 2 * i + 2;
if (left_child < n && A[left_child] > A[largest])
largest = left_child;
if (right_child < n && A[right_child] > A[largest])
largest = right_child;
if (largest != i) {
swap(A[i], A[largest]);
heapify(A, n, largest);
}
}
void heap_sort(int A[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(A, n, i);
for (int i = n - 1; i >= 0; i--) {
swap(A[0], A[i]);
heapify(A, i, 0);
}
}
void printArray(int A[], int n)
{
for (int i = 0; i < n; ++i)
cout << A[i] << " ";
cout << "\n";
}
int main()
{
int A[] = { 22, 19, 3, 25, 26, 7 };
int n = sizeof(A) / sizeof(A[0]);
heap_sort(A, n);
cout << "Sorted array is \n";
printArray(A, n);
}