排序---插入排序

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;
}

猜你喜欢

转载自www.cnblogs.com/iwangzhengchao/p/10009999.html