您的位置:首页 > 其它

堆排序

2014-06-30 14:56 176 查看
今天研究学习了下数据结构中的堆排序算法,据此自己写了一个完整的算法来实践下。

//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
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: