排序---插入排序

1. 插入排序html

插入排序Insert Sort)是一種簡單直觀的排序算法。它的工做原理是經過構建有序序列,對於未排序數據,在已排序序列中從後向前掃描,找到相應位置並插入。插入排序在實現上,一般採用in-place排序(即只需用到O(1)的額外空間的排序),於是在從後向前掃描過程當中,須要反覆把已排序元素逐步向後挪位,爲最新元素提供插入空間。【詳情見維基百科ios

使用插入排序爲一列數字進行排序的過程以下圖:算法

插入排序
Insertion sort animation.gif
使用插入排序爲一列數字進行排序的過程
分類 排序算法
數據結構 數組
最壞時間複雜度 O(n^{2})
最優時間複雜度 O(n)
平均時間複雜度 O(n^{2})
最壞空間複雜度 總共O(n) ,須要輔助空間O(1)
 
2.  插入排序C++
#include<iostream>
#include<vector>
using namespace std;

void InsertSort(vector<int> &array){
    for(int i = 1; i < array.size(); i++){
        if(array[i] < array[i-1]){
            int temp = array[i];
            int j = i;
            while(j >= 1 && temp < array[j-1]){
                array[j] = array[j-1];
                j--;
            }
            array[j] = temp;
        }
    }
}


int main(int argc, char const *argv[])
{
    vector<int> a1 = {5, 9, 0, 1, 3, 6, 4, 8, 2, 7};
    InsertSort(a1);
    for(auto &it : a1)
        cout<<it<<' ';
    cout<<endl;

    return 0;
}

 3. 使用大量數據進行測試數組

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

void InsertSort(vector<int> &array){
    for(int i = 1; i < array.size(); i++){
        if(array[i] < array[i-1]){
            int temp = array[i];
            int j = i;
            while(j >= 1 && temp < array[j-1]){
                array[j] = array[j-1];
                j--;
            }
            array[j] = temp;
        }
    }
}


// 判斷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;
}

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

    clock_t start = clock();
    InsertSort(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;
}

對20萬隨機數據的排序結果以下:數據結構

Time goes: 104.172sec
1
[Finished in 105.6s]

可見,耗時少於選擇排序,可是大於其餘快速排序算法。測試

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

相關文章
相關標籤/搜索