插入排序的基本思想是每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子文件中的适当位置,直到全部记录插入完成为止。常见的插入排序有插入排序(Insertion Sort),希尔排序(Shell Sort),二叉查找树排序(Tree Sort),图书馆排序(Library Sort),Patience排序(Patience Sort)。下面介绍前两种:
(一)直接插入排序
最差时间复杂度:O(n^2)
最优时间复杂度:O(n)
平均时间复杂度:O(n^2)
稳定性:稳定
直接插入排序(Insertion Sort),是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对未排序的数据,在已排序序列中从后向前扫描,找到相应位置并插入。
插入排序算法的一般步骤:
1.从第一个元素开始,该元素可以认为已被排序;
2.取出下一个元素,在已经排序的元素序列中从后向前扫描;
3.如果该元素(已排序)大于新元素,将该元素移到下一个位置;
4.重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
5.将新元素插入到该位置后,重复2~5
算法示意图:
算法伪代码如下:
insertSort(A)
1:for i=1 to A.length-1
2: key=A[i] //将待插入数当成key哨兵
3: j=i
4: while j>0 且 a[j]<a[j-1]
5: a[j]=a[j-1]
6: a[j-1]=key
7: a[j]=key
代码实现如下
#include<iostream>
using namespace std;
void insertSort(int a[],int n);
void print(int a[],int n);
int main()
{
int a[] = { 3, 1, 4, 8, 9, 10, 3, 4, 7 };
insertSort(a, 9);
}
void insertSort(int a[], int n)
{
/*for (int i = 1; i < n; i++)
{
for (int j = i; j >0;j--)
if (a[j] < a[j - 1])
{
int x = a[j];
a[j] = a[j - 1];
a[j - 1] = x;
}
cout << "the result is" << endl;
print(a, n);
cout << "_ _ _ _ _ _ _ _ _ _ _ _ _ _" << endl;
}*/
for (int i = 1; i < n; i++)
{
int x = a[i];
int j = i;
while ((j>0)&&(a[j] < a[j-1]))
{
a[j] = a[j - 1];
a[j - 1] = x;
--j;
}
a[j] = x;
cout << "the result is" << endl;
print(a, n);
cout << "_ _ _ _ _ _ _ _ _ _ _ _ _ _" << endl;
}
}
void print(int a[], int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
排序后结果如下: