zoukankan      html  css  js  c++  java
  • 排序之堆排序

        对于堆排序,我觉得算法导论上写的已经很好了,没学过的可以去看一下。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    #define LEFT(i) (2*i+1)
    #define RIGHT(i) (2*i+2)
    
    //从数组最后一个开始建堆。每次都是在[i+1,n]已经排好的基础上建堆
    void build_heap(int* a,int n,int i)
    {
        int target = i;
        int l=LEFT(i),r = RIGHT(i);
        if(l < n)
            target = a[target] > a[l] ? target : l;
        if(r < n)
            target = a[target] > a[r] ? target : r;
        if(target==i) return;
        swap(a[i],a[target]);
        build_heap(a,n,target);
    }
    
    void heapSort(int* a,int n)
    {
        //建堆
        //如果求简单i从n-1也可以。
        for(int i=n/2;i>=0;--i)
            build_heap(a,n,i);
        //排序
        for(int i=n-1;i>=1;--i)
        {
            swap(a[i],a[0]);
            build_heap(a,i,0);
        }
    }
    
    int main()
    {
        int a[] = {8,4,10,9,1,3,7,5,2,6};
        int n = sizeof(a) / sizeof(int);
        heapSort(a,n);
        for(int i=0;i<n;++i)
            printf("%d ",a[i]);
        printf("
    ");
        return 0;
    }
  • 相关阅读:
    leetcode-19-merge
    leetcode-18-remove
    R-codes-tips
    python-bioInfo-codes-2
    Java-framework-Vaadin
    leetcode-17-BST
    生物信息学-知识笔记-1
    leetcode-16-greedyAlgorithm
    perl-tips-1
    计算机网络HTTP、TCP/IP包
  • 原文地址:https://www.cnblogs.com/jlyg/p/6692074.html
Copyright © 2011-2022 走看看