插入排序:O(n^2)
思路:将排序数组逻辑上分为两部分,一部分已经拍好续的(哪怕就一个数,或者没有),其余的为另一部分(未排序),读取未排序的部分,将值插入到已经排序过的序列的对应位置。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
void genrand(int num,long * array){
if(num<0 || num >100)
return;
srand((unsigned int)time(0));
while(num--)
array[num] = rand();
}
void halfInsertSort(long * array,int length){
if(array==NULL || length<=0)
return;
int i,j,tmp;
for(i=1;i<length;i++){
tmp = array[i];
int low = 0;
int hight = i-1;
while(low<=hight){
int mid = (low+hight)/2;
if(array[mid] > tmp)
hight = mid-1;
else
low = mid+1;
}
for(j=i-1;j>=low;j--){
array[j+1] = array[j];
}
array[low] = tmp;
}
}
int main(int argc,char * argv){
int num = 10;
long * array = (long *)malloc(sizeof(long)*num);
genrand(num,array);
halfInsertSort(array,num);
while(num--)
printf("%ld\n",array[num]);
return 0;
}
ubuntu14.04,vim,gcc