排序---插入排序

1. 插入排序

插入排序Insert Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。【详情见维基百科

使用插入排序为一列数字进行排序的过程如下图:

插入排序
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]

可见,耗时少于选择排序,但是大于其他快速排序算法。

点击此处查看常用排序算法

posted on 2018-11-23 22:11  wangzhch  阅读(1226)  评论(0编辑  收藏  举报

导航