今天研究学习了下数据结构中的堆排序算法,据此自己写了一个完整的算法来实践下。
//The beginning index of arrary is 0, not 1.
int raw_arr[10] = {4,2,3,6,7,3,1,9,10,8};
void sift(int* r, int l, int m)
{
int i,j;
i = l; //i is the start node to keep heap
j = 2 * i + 1; //j is left subnode, j+1 is right subnode
//m is the size of current heap
while (j < m) {
//if r[i] has right subnode, then compare it with left subnode.
if (j + 1 < m
&& r[j] < r[j+1])
j = j+1;
if (r[i] < r[j]) {
int tmp = r[i];
r[i] = r[j];
r[j] = tmp;
i = j;
j = 2*i + 1;
} else {
break; //if r[i] is not less than it's left and right subnodes, then break;
}
}
}
void heapsort(int* array, int n)
{
int i;
//build heap, start from array index n/2 -1 to 0
for (i = n/2 - 1; i >= 0; i--) {
sift(array, i, n);
}
//sort, heapsize reduce from n to 2
for (i = n; i >= 2; i--) {
//exchange the maximum value array[0] with the last element in current heap
int m = array[i - 1];
array[i - 1] = array[0];
array[0] = m;
//after exchange, heapsize reudce 1 and keep new heap whose headsize is i - 1
if (2 > i-1) break; //it's not necessary to keep heap when heapsize is less than 2
sift(array, 0, i-1); //heapsize is i - 1
}
}