Heap Sort
This is a new heap sort code, you can copy it, and paste in linux, then run it.
Show code
#include <stdio.h>
/*- print function -*/
void print_array(int *pArray, int length)
{
int i;
for (i = 0; i < length; i++) {
printf("%d ", pArray[i]);
}
printf("\n");
}
void swap_value(int *pArray, int left, int right)
{
int temp = pArray[left];
pArray[left] = pArray[right];
pArray[right] = temp;
}
void max_heap(int *pArray, int index, int length)
{
int leftIndex = (index << 1) + 1;
int rightIndex = (index << 1) + 2;
/*if left inex beyond length, ignore it */
if (leftIndex <= length-1) {
/* check left child-node */
if (pArray[index] < pArray[2*index+1]) {
swap_value(pArray, index, 2*index+1);
}
}
/* only handle normal index */
if( rightIndex <= length-1) {
/* check right child-node */
if (pArray[index] < pArray[2*index+2]) {
swap_value(pArray, index, 2*index+2);
}
}
}
void heapify(int *pArray, int index, int length)
{
if (length < 3) {
/*only two elements, just return. */
return;
}
if (index > length - 1) {
return;
}
int i = index;
/* recurise */
int leftIndex = 2*i+1;
int rightIndex = 2*i+2;
max_heap(pArray, i, length);
/*check sub-children match max_heap or not and adjust it. */
heapify(pArray, leftIndex, length);
heapify(pArray, rightIndex, length);
}
void heap_sort(int *pArray, int length)
{
int i = length;
while(i >= 1) {
int j = (i/2-1);
/*build max-top heap */
while(j >= 0) {
heapify(pArray, j, i);
j--;
}
swap_value(pArray, 0, i-1);
i--;
print_array(pArray, length);
}
}
int main(int argc, char *argv[])
{
int aszArray[] = {60, 70, 90, 20, 80, 10};
print_array(aszArray, 6);
heap_sort(aszArray, 6);
printf("-------------\n");
print_array(aszArray, 6);
return 0;
}