堆排序

作者: 刘小小gogo | 来源:发表于2018-10-12 19:43 被阅读0次
    #include <iostream>
    using namespace std;
    //void heapify(int a[], int startindex, int length){
    //    while( (2*startindex + 1) < length){
    //        int index = startindex;
    //        int maxx = a[startindex];
    //        if(a[2*startindex+1] > maxx) {
    //            index = 2 * index + 1;
    //            maxx = a[index];
    //        }
    //        if(a[2 * startindex + 2] > maxx && 2 * startindex + 2 <length){
    //            index = 2 * index + 2;
    //            maxx = a[index];
    //
    //        }
    //        if(startindex == index) break;
    //        swap(a[startindex], a[index]);
    //        startindex = index;
    //    }
    //}
    
    void heapify(int a[], int startindex, int length){
        int tmp = a[startindex];
        int index = startindex;
        for(int k = 2 * startindex + 1; k < length; k=2*k+1){
            if(k+1 < length && a[k] < a[k+1]){
                k++;
            }
    
            if(a[k] > a[index]){
                swap(a[index], a[k]);
                index = k;
            }
            else{
                break;
            }
        }
    
    }
    void heapSort(int a[], int length){
        for(int i = length/2 -1; i >= 0; i--){
            heapify(a, i, length);
        }
    
        for(int i = length - 1; i > 0; i-- ){
            swap(a[0], a[i]);
            heapify(a, 0, i);
        }
    }
    
    
    int main() {
        int a[10] = {9,7,3,4,1,5,2,6,10,8};
        heapSort(a,10);
        for(int i = 0; i < 10; i++){
            cout<<a[i]<<" ";
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:堆排序

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