直接插入排序算法
原创
©著作权归作者所有:来自51CTO博客作者油菜花11的原创作品,请联系作者获取转载授权,否则将追究法律责任
插入排序算法是所有排序方法中最简单的一种算法,其主要的实现思想是将数据按照一定的顺序一个一个的插入到有序的表中,最终得到的序列就是已经排序好的数据。
直接插入排序是插入排序算法中的一种,采用的方法是:在添加新的记录时,使用顺序查找的方式找到其要插入的位置,然后将新记录插入。
看下面这段代码,理解下:一个一个插入这个概念。
在while循环里所做的就是找到要插入的位置
void InsertSort(int a[], int n)
{
// 默认情况下第一个 是直接放进去的
for(int iPos =1; iPos<n; iPos++)
{
int iAddElem = a[iPos]; // 当前新增元素
int iPreElem = iPos-1;
while(iAddElem<a[iPreElem]&&(iPreElem >=0))
{
a[iPreElem +1] = a[iPreElem];
iPreElem--;
}
a[iPreElem+1] = iAddElem;
}
}
时间复杂度,考虑到极限情况:
第一次找位置用到的次数: n-1
第二次n-2
第三次 :n-3
第N次 :0
求和: (n-1)n/2 = 1/2n^2,所以复杂度为 O(n2)
#include <iostream>
#include <windows.h>
using namespace std;
#define SWAP(X,Y) X=X+Y;Y=X-Y;X=X-Y
void PrintArray(int *Array, int iSize)
{
for (int i = 0; i < iSize; i++)
{
cout << "Current Value is " << Array[i] << endl;
}
}
void InsertSort(int a[], int n)
{
int iNowElem, iSentry;
for (int i = 1; i < n; i++)
{
iNowElem = a[i]; // 当前元素
iSentry = i - 1; // 前一个元素位置
while(iSentry >= 0 && iNowElem < a[iSentry])
{
a[iSentry + 1] = a[iSentry];
iSentry--;
}
a[iSentry + 1] = iNowElem;
}
}
int main()
{
int a[10] = { 10,9,8,7,6,5,4,3,2,1 };
InsertSort(a, 10);
PrintArray(a,10);
system("pause");
return 0;
}