// 数据结构_插入排序.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define array_length 100
/*算法导论中的伪代码
INSERTION-SORT(A)
1 for j = 2 to length(A)
2 do key <- A[j]
3 // Insert A[j] into the sorted sequence A[1,j-1]
4 i = j - 1;
5 while i > 0 and A[i] > key
6 do A[i+1] <- A[i]
7 i <- i - 1;
8 A[i+1] <- key
插入排序的时间复杂度: N*N
*/
int paixu_charu(int a[],int length){
int i = 0,j = 0;
int shaobing = 0;
for(j = 1; j < length;j++){
shaobing = a[j];
i = j - 1;
/*这里我们设置后面一个数为哨兵,当第i个数,也就是哨兵前面一个数大于哨兵时,哨兵跟这个数换位置,哨兵的值不变,哨兵不断的前移
不断的比较,所以这里我们时间复杂度最换为N*N*/
while((i >= 0)&&(a[i] > shaobing)){
a[i+1] = a[i];
i = i - 1;
a[i+1] = shaobing;
}
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[array_length];
int icycle = 0;
/*随机数生成*/
printf("cha ru paixu before:\n");
for(icycle = 0; icycle < array_length;icycle++){
a[icycle] = ( (rand() + rand()) + icycle)*(array_length/(icycle+2));
printf("%d ",a[icycle]);
}
printf("\n");
paixu_charu(a,array_length);
printf("cha ru paixu after:\n");
for(icycle = 0; icycle < array_length;icycle++){
printf("%d ",a[icycle]);
}
printf("\n");
/**/
return 0;
}