1. 插入排序
插入排序(Insert Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用in-place排序(即只需用到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; }