排序---堆排序

堆排序html

1. 堆排序ios

  堆排序(Heapsort)是指利用這種數據結構所設計的一種排序算法。堆是一個近似徹底二叉樹的結構,並同時知足堆積的性質:即子結點的鍵值或索引老是小於(或者大於)它的父節點。詳情見堆排序【維基百科】算法

堆排序
Sorting heapsort anim.gif
堆排序算法的演示。首先,將元素進行重排,以匹配堆的條件。圖中排序過程以前簡單的繪出了堆樹的結構。
分類 排序算法
數據結構 數組
最壞時間複雜度 O(n\log n)
最優時間複雜度 O(n\log n)[1]
平均時間複雜度 \Theta (n\log n)
最壞空間複雜度 O(n) total, O(1) auxiliary

 

2. 堆排序實現數組

#include<iostream>
#include<vector>
#include <stdlib.h>
#include <time.h>
using namespace std;

void HeapAdjust(vector<int> &array, int start, int end){
    int dad = start;
    int son = 2 * dad + 1;
    while(son <= end){
        if(son + 1 <= end && array[son] <= array[son+1])
            son += 1;
        if(array[dad] > array[son])
            return ;
        else{
            swap(array[dad], array[son]);
            dad = son;
            son = 2 * dad + 1;
        }
    }
}

void HeapSort(vector<int> &array){
    for(int i = array.size()/2-1; i >= 0; i--){
        HeapAdjust(array, i, array.size()-1);
    }
    for(int j = array.size()-1; j >= 0; j--){
        swap(array[0], array[j]);
        HeapAdjust(array, 0, j-1);
    }
}
// 判斷array是否有序
bool isOrder(vector<int> &array){
    for(int i = 1; i < array.size(); i++){
        if(array[i] < array[i-1])
            return false;
    }
    return true;
}

// 生成n個介於min,max之間的整型數
vector<int> RAND(int max, int min, int n) {
    vector<int> res;
    srand(time(NULL)); // 註釋該行以後,每次生成的隨機數都同樣
    for(int i = 0; i < n; ++i) {
        int u = (double)rand() / (RAND_MAX + 1) * (max - min) + min;
        res.push_back(u);
    }
    return res;
}

// 使用20000000個介於1,10000之間的數據進行測試
int main(int argc, char const *argv[]) {
    vector<int> a = RAND(1, 10000, 20000000);

    clock_t start = clock();
    HeapSort(a);
    clock_t end   = clock();
    cout << "Time goes: " << (double)(end - start) / CLOCKS_PER_SEC << "sec" << endl;

    bool sorted = isOrder(a);
    cout<<sorted<<endl;
    return 0;
}

 

3. 運行結果數據結構

使用20000000個介於1,10000之間的數據進行測試,運行結果以下:測試

Time goes: 25.169sec
1
[Finished in 27.4s]

點擊此處查看經常使用排序算法spa