1、直接插入排序
1 #include<stdio.h> 2 3 struct node 4 { 5 int key; 6 }; 7 typedef struct node DataType; 8 9 int Ins_Sort(DataType Ar[],int n); 10 11 int main(void) 12 { 13 14 int n,i; 15 DataType array[20]; 16 17 printf("Input the length of the array <<20>:"); 18 scanf("%d",&n); 19 for(i=0; i<n; i++) //輸入數組 20 { 21 printf("Input %d datas:",i+1); 22 scanf("%d",&array[i]); 23 } 24 25 printf("\n The array are:"); 26 for(i=0; i<n; i++) 27 { 28 printf("%4d",array[i]); //輸入的數組顯示 29 } 30 31 Ins_Sort(array, n); 32 33 printf("\n The array after Ins_Sort are:"); 34 for(i=0; i<n; i++) //輸出排序后的算法結果 35 { 36 printf("%4d",array[i]); 37 } 38 return(0); 39 } 40 41 42 int Ins_Sort(DataType Ar[],int n) //直接插入排序算法 43 { 44 int i,j; 45 DataType temp; 46 for(i=1;i<n;i++) //總共要進行n-1掃描 47 { 48 temp=Ar[i]; //每次掃描總是把被考察排序碼存入臨時單元 49 j=i-1; //j規定了這次比較范圍的上界 50 while((temp.key<Ar[j].key)&&(j>=0)) 51 { 52 Ar[j+1]=Ar[j]; 53 j--; 54 } 55 Ar[j+1]=temp; //完成插入 56 } 57 }
2、直接選擇排序算法
1 #include<stdio.h> 2 3 struct node 4 { 5 int key; 6 }; 7 typedef struct node DataType; //DataType是struct node的別名 8 9 int Sel_sort(DataType Ar[],int n); //聲明直接選擇排序算法 10 11 int main(void) 12 { 13 14 int n,i; 15 DataType array[20]; 16 17 printf("Input the length of the array <<20>:"); 18 scanf("%d",&n); 19 for(i=0; i<n; i++) //輸入數組 20 { 21 printf("Input %d datas:",i+1); 22 scanf("%d",&array[i]); 23 } 24 25 printf("\n The array are:"); 26 for(i=0; i<n; i++) 27 { 28 printf("%4d",array[i]); //輸入的數組顯示 29 } 30 31 Sel_sort(array,n); //調用排序算法 32 printf("\n The array after Sel_sort are:"); 33 for(i=0; i<n; i++) //輸出排序后的算法結果 34 { 35 printf("%4d",array[i]); 36 } 37 return(0); 38 } 39 40 int Sel_sort(DataType Ar[],int n) //直接選擇排序算法 41 { 42 DataType temp; 43 int i,small,j; 44 for(i=0; i<=n-1; i++) //i控制n-1趟掃描 45 { 46 small=i; //用變量small記住當前最小排序碼的位置 47 for(j=i+1; j<n; j++) //j控制這趟掃描的比較范圍 48 if(Ar[j].key<Ar[small].key) //如果發現更小者,隨時修改small的值 49 small=j; 50 if(small!=i) //small與比較范圍首元素下標不同,則交換 51 { 52 temp=Ar[i]; //交換是利用臨時變量temp進行的 53 Ar[i]=Ar[small]; 54 Ar[small]=temp; 55 } 56 } 57 } 58 //直接選擇排序的效率與初始狀態無關,即無最好最壞的情況.時間復雜度為O(n*n),不是穩定的排序算法
