堆排序

作者: 凌霄文强 | 来源:发表于2019-03-11 14:58 被阅读0次
    #include<iostream>
    using namespace std;
    int main(){
        int a[]={6,3,4,1,7,2,9,55,77,11,88,5};
        int length=sizeof(a)/sizeof(a[0])-1;
        for(int i=(length-1)/2; i>=0; i--){
            int j=i;
            while(true){
                if(j*2+1>length || (j*2+2>length && a[j]>=a[j*2+1]) || (j*2+2<=length && a[j]>=a[j*2+1] && a[j]>=a[j*2+2]))
                    break;
                if(j*2+2>length || a[j*2+1]>a[j*2+2]){
                    swap(a[j],a[j*2+1]);
                    j=j*2+1;
                }
                else{
                    swap(a[j],a[j*2+2]);
                    j=j*2+2;
                }
            }
        }
        swap(a[0],a[length]);
    
        for(int length=sizeof(a)/sizeof(a[0])-2; length>0; length--){
            int j=0;
            while(true){
                if(j*2+1>length || (j*2+2>length && a[j]>=a[j*2+1]) || (j*2+2<=length && a[j]>=a[j*2+1] && a[j]>=a[j*2+2]))
                    break;
                if(j*2+2>length || a[j*2+1]>a[j*2+2]){
                    swap(a[j],a[j*2+1]);
                    j=j*2+1;
                }
                else{
                    swap(a[j],a[j*2+2]);
                    j=j*2+2;
                }
            }
            swap(a[0],a[length]);
            for(int i=0; i<sizeof(a)/sizeof(a[0]); i++)
                cout<<a[i]<<"  ";
            cout<<endl;
        }
        return 0;
    }
    

    相关文章

      网友评论

        本文标题:堆排序

        本文链接:https://www.haomeiwen.com/subject/zhhbpqtx.html