2011-09-20 20 views
0

我無法弄清楚它出了什麼問題。請幫我調試我的插入排序程序

如果輸入:4,56,5,2,則顯示的輸出爲:2,4,0,1304。

如果輸入:27,54,43,26,2然後所示的輸出是:2,26,0,1304,0

如果輸入:34,87,54,4,34然後輸出示出的是:4,34,0,1304,0

基本上,只有前兩個排序的nos被顯示在輸出和其他地方,對於任何一組輸入都顯示1304或0。

#include <conio.h> 
#include <stdio.h> 
void main() 
{ 
    int a[10],b[10]; 
    int i,size,j,k; 
    clrscr(); 
    printf("please tell how many nos you want to enter"); 
    scanf("%d",&size); 
    printf("Enter the nos"); 
    for (i=0;i<size;i++) scanf("%d",&a[i]); 
    b[0]=a[0]; 
    //insertionSort algo ----> 
    for (j=1;j<size;j++) 
    { 
    for (k=j-1;k>=0;k--) 
     //handling comparision with b[0] 
     if (k==0&&(a[j]<b[0])) { 
     b[1]=b[0]; 
     b[0]=a[j]; 
     } 
    //handling comparison with b[1:size-1] 
    if (k>0&&(a[j]<b[k])) { b[k+1]=b[k]; } 
    if (k>=0&&(a[j]>=b[k])) { b[k+1]=b[k]; break; } 
    } 
    for (i=0;i<size;i++) printf("%d\n",b[i]); 
    getch(); 
} 
+0

有什麼預期的結果? –

+1

預期結果是輸入的數字以升序排列顯示 – Pradeep

+0

邏輯極端有缺陷。拿出一張紙,畫出你認爲這個程序應該如何工作。看起來你沒有先理解程序就開始編碼。 – Coeffect

回答

0

使用算法更簡單:

  1. 閱讀的數字,數組複製A到B之後保持原有的輸入。

  2. 對於升序排序,令i = 0,J = i + 1的

  3. 循環Ĵ直到陣列的結束時,如果B [j]的< B [I]然後交換兩個數字。

  4. 增加i,設定j = i + 1,轉到第3步。除非i> =大小。

  5. 打印陣列A和B

該算法可以在以後進行優化。

+1

雖然你的排序算法,但它不是插入排序specific.In插入排序,你添加另一個no到一個排序列表,這樣的結果列表也排序。例如:插入排序用於排序播放牌。 – Pradeep

+0

事實上,爲此我寧願鏈接列表,而不是數組。 –

0

下面是與/* comments */最小的變化,使您的工作方案:

#include <conio.h> 
#include <stdio.h> 
void main() 
{ 
    int a[10],b[10]; 
    int i,size,j,k; 
    clrscr(); 
    printf("please tell how many nos you want to enter"); 
    scanf("%d",&size); 
    printf("Enter the nos"); 
    for (i=0;i<size;i++) scanf("%d",&a[i]); 
    b[0]=a[0]; 
    //insertionSort algo ----> 
    for (j=1;j<size;j++) 
    for (k=j-1;k>=0;k--) 
    { /* the inner loop must contain all the if statements */ 
     //handling comparision with b[0] 
     if (k==0&&(a[j]<b[0])) { 
     b[1]=b[0]; 
     b[0]=a[j]; 
     break; /* done; don't mess with b[0+1] below */ 
     } 
     //handling comparison with b[1:size-1] 
     if (k>0&&(a[j]<b[k])) { b[k+1]=b[k]; } 
     if (k>=0&&(a[j]>=b[k])) { b[k+1]=a[j]; break; } /* =a[j] */ 
    } 
    for (i=0;i<size;i++) printf("%d\n",b[i]); 
    getch(); 
}