Skip to content

Instantly share code, notes, and snippets.

@Kokajinum
Created December 29, 2017 11:49
Show Gist options
  • Save Kokajinum/4b806d7bf53ed43508febeac6d387e87 to your computer and use it in GitHub Desktop.
Save Kokajinum/4b806d7bf53ed43508febeac6d387e87 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define LENGTH 10
int heapSize;
void Heapify(int* A, int i)
{
int l = 2 * i + 1;
int r = 2 * i + 2;
int largest;
if(l <= heapSize && A[l] > A[i])
largest = l;
else
largest = i;
if(r <= heapSize && A[r] > A[largest])
largest = r;
if(largest != i)
{
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
Heapify(A, largest);
}
}
void BuildHeap(int* A)
{
heapSize = LENGTH - 1;
int i;
for(i = (LENGTH - 1) / 2; i >= 0; i--)
Heapify(A, i);
}
void HeapSort(int* A)
{
BuildHeap(A);
int i;
for(i = LENGTH - 1; i > 0; i--)
{
int temp = A[heapSize];
A[heapSize] = A[0];
A[0] = temp;
heapSize--;
Heapify(A, 0);
}
}
int main()
{
int tab[LENGTH] = {1,4,2,6,7,5,8,2,3,3};
HeapSort(tab);
int i;
for(i = 0; i < LENGTH; i++)
printf("%d ",tab[i]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment