堆排序

今天研究学习了下数据结构中的堆排序算法,据此自己写了一个完整的算法来实践下。


//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
    }
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值