2013-02-11 41 views
4

說我有號碼的清單:C編程:如何實現插入排序?

89 12 18 4 6 

,我想實現一個插入排序,並把它打印之類的每一步都在屏幕上:

Sort 1. 12 89 18 4 6 
Sort 2. 4 12 89 18 6 
Sort 3. 4 6 12 89 18 
Sort 4. 4 6 12 18 89 

這裏的代碼到目前爲止,我對將循環中的printf插入到哪裏感到困惑。

void insertion_sort(FILE *fp, int ar[15]) 
{ 
    int i, j, temp; 

    for (i = 0; i < 15; i++) 
    printf("%d\n", ar[i]); 

    for(i = 0; i < 15; i++) { 
    temp = ar[i]; 
    for(j = i - 1; j >= 0 && ar[j] > temp; j--) 
     ar[j + 1] = ar[j]; 
    ar[j + 1] = temp; 
}  
+1

插入外for循環內的printf()的,因爲要打印你在每一步排數組。 – 2013-02-11 08:00:02

+0

你的排序是否適用?我想你需要將第二個for循環代碼包裝在inner for循環中 – exexzian 2013-02-11 08:00:44

回答

0

把它放在ar [j + 1] = temp之後的語句外部的末尾;而對於循環結束

1

您的排序方案之前,實際上是選擇排序:

Sort 1. 12 89 18 4 6 
    Sort 2. 4 12 89 18 6 
    Sort 3. 4 6 12 89 18 
    Sort 4. 4 6 12 18 89 

發現在列表的開頭的最小數量和地點吧。 正常插入排序將執行以下操作:

Sort 1. 12 89 18 4 6 
    Sort 2. 12 18 89 4 6 
    Sort 3. 4 12 18 89 6 
    Sort 4. 4 6 12 18 89 

,那就是它發現18小於89但大於12,並插入18 12和89之間以及在第一迭代完成。然後重複這個過程。

這是我的代碼:

void insertion(int *x,int n){ // int *x - array, n- array's length 
    int i,j,k,temp,elem; // i,j,k - counters, elem - to store the element at pos x[i] 
    for(i=0;i<n;i++){ 
     elem=x[i]; // store the element 
     j=i; 
     while(j>0 && x[j-1]>elem){ // the magic(actual sorting) 
      x[j]=x[j-1]; 
      j--; 
     } 
     x[j]=elem; // swap the elements 
     if(i>=1){ // here begins printing every sorting step, i>=1 because first time j is not greater than 0 so it just run through the loop first time 
     printf("sort %d. ",i); // printing the step 
     for(k=0;k<n;k++) // loop through array 
      printf("%d ",x[k]); // display the elements already sorted 
     printf("\n"); // when the array is displayed, insert a \n so that the next display will be on a new line 
     } 
    } 
}