一.算法描述
一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:
1. 从第一个元素开始,该元素可以认为已经被排序
2. 取出下一个元素,在已经排序的元素序列中从后向前扫描
3. 如果该元素(已排序)大于新元素,将该元素移到下一位置
4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
5. 将新元素插入到该位置后
6. 重复步骤2~5
二.时间复杂度
1.最好情况:如果数组本身是排序的,使用插入排序算法,比较次数为n-1,交换次数为0,因此,最好情况下,插入排序的时间复杂度为O(n).
2.最差情况:如果数组本身是逆序的,使用插入排序算法,比较的次数为(1+2+...+n-1=n(n-1)/2),交换次数和比较次数一样,因此,在最差情况下,插入排序的时间复杂度为O(n^2).
3.平均情况:在平均情况下的时间代价是最差情况下的一半,因此,平均情况下,插入排序的时间复杂度也为O(n^2).
三.空间复杂度
插入排序是in-place的排序,空间复杂度为O(1)。
四.C++实现
#include <iostream>
#include "Sort.h"
bool InsertSort(std::vector<int>& Array)
{
// return false if the array is empty.
if (Array.empty())
{
std::cout << "The size of the Array is empty." << std::endl;
return false;
}
// return the origin array if there are only one element of the array
if (Array.size() == 1)
{
std::cout << "The size of the array is one." << std::endl;
return true;
}
int Size = Array.size();
for (int Index = 1; Index < Size; Index++)
{
int Value = Array[Index];
int TrueIndex = Index - 1;
// find the index of the Value
for (; TrueIndex >=0; TrueIndex--)
{
if (Array[TrueIndex] <= Value)
{
break;
}
Array[TrueIndex + 1] = Array[TrueIndex];
}
// put the value to the TrueIndex
Array[TrueIndex + 1] = Value;
}
return true;
}
五.参考文献
[1] Shaffer C A. Practical Introduction to Data Structure and Algorithm Analysis (C++ Edition)[J]. 2002.
[2] 科曼 and 金贵, 算法导论: 机械工业出版社, 2006.
[3] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, "算法导论 (影印版)," ed: 北京: 高等教育出版社.
[4]http://zh.wikipedia.org/wiki/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95
版权所有,欢迎转载,转载请注明出处,谢谢
