美文网首页
堆排序(最小堆)

堆排序(最小堆)

作者: 希崽家的小哲 | 来源:发表于2015-05-22 09:47 被阅读51次
    #include<iostream>
    #define SIZE 123456
    #define K 100
    using namespace std;
    void swap(int *a,int *b){
        int temp;
        temp = *a;
        *a = *b;
        *b = temp;
    }
    void HeapAdjust(int array[],int i,int length)
    {
        int left    = i*2;
        int right   = i*2+1;
        int largest = i;
        if (left<=length && array[left] < array[largest]) {
            largest     = left;
        }
        if (right<=length && array[right] < array[largest]) {
            largest     = right;
        }
        if (largest!=i) {
            swap(&array[largest], &array[i]);
            HeapAdjust(array, largest, length);
        }
    }
    
    void BuildHeap(int array[],int length)
    {
        for (int i=length/2; i>=1; i--) {
            HeapAdjust(array, i, length);
        }
    }
    
    void HeapSort(int array[],int length)
    {
        BuildHeap(array, length);
        for (int i=length; i>=2; i--) {
            swap(&array[i], &array[1]);
            HeapAdjust(array, 1, i-1);
        }
    }
    int main(){
        int test[] = {0,4,1,3,2,16,9,10,14,8,7};
        for(int i = 1; i <= 10; i++)
            cout<<test[i]<<"  ";
        cout<<endl;
        HeapSort(test,10);
        for(int i = 1; i <=10; i++)
            cout<<test[i]<<"  ";
        cout<<endl;
        return 0;
    }
    

    4 1 3 2 16 9 10 14 8 7
    16 14 10 9 8 7 4 3 2 1
    Program ended with exit code: 0

    相关文章

      网友评论

          本文标题:堆排序(最小堆)

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