/*
* 插入排序,从小到大
* 假定第一个是最小的,后面的值依次与前面的值从右往左比较,如果后面的小就把前面的值填到自己的位置
* 并重复继续往左比较(否则不动,继续下一个值判断),直到找到比自己小的值,把自己的值填到其后面
*
*时间复杂度 最好O(n) 最坏O(n^2) 平均还是O(n^2)
*稳定性:稳定
*原地排序:是
*排序 n-1趟
*/
void insertSort(int src[], int len){
//4, 6, 6, 1, 3 ->
//1 6 4 3
//1 4 6 3
//1 4 3 6
register int i,j, temp = 0;
for(i=0; i<len-1; i++){
temp = src[i+1];//待插入值
for(j=i; j>=0; j--){
if(temp<src[j]){//稳定性在=时插在后面
//如果temp比该值小则该值后移
src[j+1] = src[j];
}
else{
break;
}
}
src[j+1] = temp;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
//test();
int nums[] = {2, 1, 5, 9, 4, 3, 3, 6, 7, 8, 10};
int len = sizeof(nums)/sizeof(int);
for(int i=0; i<len; i++){
cout<<nums[i]<<" ";
}cout<<endl;
//bubbleSort(nums, len);
//selectSort(nums, len);
insertSort(nums, len);
for(int i=0; i<len; i++){
cout<<nums[i]<< " ";
}cout<<endl;
getchar();
return 0;
}