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

      

    #include <iostream>
    #define len(x) (unsigned int)sizeof(x)/sizeof(x[0])
    
    using namespace std;
    
    void Swap(int x[],int i,int j){
    //    int tem = x[i];
    //    x[i] = x[j];
    //    x[j] = tem;
    //
    //    x[i]^=x[j];
    //    x[j]^=x[i];
    //    x[i]^=x[j];
        x[i] = x[i]+x[j];
        x[j] = x[i]-x[j];
        x[i] = x[i]-x[j];
    }
    
    void print(int x[],int length){
        for(int i = 0; i < length; i++){
            cout << x[i] << "	";
        }
        cout <<endl;
    }
    
    /*heapSort Area*/
    
    void maxHeapify(int r[],int heapSize,int index){
        int left = 2*index+1;
        int right = 2*index+2;
        int larger = index;
        if(r[larger] < r[left] && left < heapSize) {//不能有left=heapSize
            larger = left;
        }else larger = index;
        if(r[larger] < r[right] && right < heapSize){//不能有left=heapSize
            larger = right;
        }
        if(larger!=index){
            Swap(r,larger,index);
            maxHeapify(r,heapSize,larger);
        }
    }
    
    int lastNode(int index){
        if(index/2==0) return (index-1)/2;
        else return (index-2)/2;
    }
    
    void buildMaxHeap(int r[],int heapSize){
        for(int i = lastNode(heapSize); i >= 0; i --){
            maxHeapify(r,heapSize,i);
        }
    }
    
    void heapSort(int r[],int length){
        int heapSize = length;
        buildMaxHeap(r,length);
        for(int i = heapSize - 1; i > 0; i--){
            Swap(r,0,heapSize-1);
    	cout << r[heapSize-1] << " is put at !" << heapSize-1 << endl;
            heapSize = heapSize-1;
            maxHeapify(r,heapSize,0);
        }
    }
    
    int main()
    {
        int r[] = {6,7,2,3,8,4,1,9,5,0};
        print(r,len(r));
        heapSort(r,len(r));
        print(r,len(r));
        return 0;
    }
    

      看了这个ppt和代码应该不会不懂了!

  • 相关阅读:
    Delphi7 (第一天:类的编写)
    设计模式(二)Abstract Factory
    hdu 3335(最小路径覆盖)
    hdu 2236(最大匹配+枚举上下界)
    hdu 2819(二分匹配)
    hdu 3861(缩点+最小路径覆盖)
    hdu 2831(贪心)
    hdu 4296(贪心)
    hdu 2354(bfs求最短路)
    hdu 4313(类似于kruskal)
  • 原文地址:https://www.cnblogs.com/luomingchuan/p/3680490.html
Copyright © 2011-2022 走看看