目錄
1.走讀插入排序代碼,算法複雜度O(n**2), 空間複雜度O(1)
1.走讀插入排序代碼,算法複雜度O(n**2), 空間複雜度O(1)
2.插入排序特性:
排序之後的前N個元素是有序的
3.以下兩段代碼
代碼一:
int sort_insert(int a[], int size)
{
int i = 0;
int j=0;
int p = 1;
int n = 0;
while(p < size){
for(i=0;i<p; i++){
if(a[i] < a[p]) continue;
int temp = a[p];
n = 0;
for(j=p;j>i;j--){
n++;
a[j] = a[j-1];
}
a[j] = temp;//j=i
printf("temp=%d, moved=%d\n", temp, n);
}
p++;
}
return 0;
}
代碼二:
int sort_insert2(int a[], int size)
{
int temp;
int j;
for(int p=1; p<size; p++){
temp = a[p];
for(j=p; j>0 && a[j-1]>temp; j--)
a[j] = a[j-1];
a[j] = temp;
}
return 0;
}
4.優缺點比較:
點1:優化空間
代碼1和代碼2雖然都能實現插入排序,但效率及優化空間就不一樣了
代碼1:
是從前往後面比較,即是從0到p-1 ,必須依次比較完
代碼2:
可以後往前比,即從p-1,p-2比較,直到比較<=temp(待插入的a[p])即可終止,有優化空間
點2:代碼行數
代碼1 25行
代碼2 12行,差一倍
點3:代碼複雜度:
代碼1明顯比代碼2要複雜,容易出錯,代碼1使用了1個while,2個for,而代碼2使用了2個for