heap_sort.c #include <stdio.h> //the value of heapSize is belong 0 and (length - 1). int heapSize = 0; //get the left index of parent int Left(int parent) { return ((parent << 1) + 1); } //get the right index of parent int Right(int parent) { return ((parent << 1) + 2); } //exchange the two values void swap(int *a, int *b) { *a ^= *b; *b ^= *a; *a ^= *b; } //modify the heap and sign that the children of array[index] have been maxheaps. void maxHeapify(int *array, int parent) { int largest = parent; int left = Left(parent); int right = Right(parent); if((left <= heapSize) && (array[left] > array[largest])) largest = left; if((right <= heapSize) && (array[right] > array[largest])) largest = right; //at this time,array[largest] has been the max(array[left],array[right],array[index]) if(largest != parent) { swap(&array[parent], &array[largest]); maxHeapify(array, largest); } } //the arg len is the max valid index of array, not the real length of array. //the process to build a maxheap is to modify the heap until the index 0 is a maxheap from index ((index_len - 1) >> 1) void buildMaxHeap(int *array, int index_len) { int i; heapSize = index_len; for(i = ((index_len - 1) >> 1);i >= 0;i--) maxHeapify(array, i); } //the arg len is the real length of array void heap_sort(int array[], int len) { int i; //initialize the max heap buildMaxHeap(array, len - 1); for(i = (len - 1);i >= 1;i--) { //exchange the array[0] which is the max value to the end sequence zone. swap(&array[0], &array[i]); //change the size of unsequence zone. heapSize--; //rebuild the maxheap and at this time the children of array[0] are all maxheap, so modify the heap on index 0 only is OK. maxHeapify(array, 0); } } void print_array(int *a, int len) { int i; for(i = 0;i < len;i++) { printf("%d ", a[i]); } printf("/n"); } int main() { int a[] = {7,9,0,3,5,1,2,6,8,4}; print_array(a, 10); heap_sort(a, 10); print_array(a, 10); return 0; }