2014-09-23 194 views
0

我需要通過其標題以簡單的方式對書對象進行排序。然而,我寫的選擇排序算法不能正常工作,只是移動書本,但沒有明顯的順序。我究竟做錯了什麼?按字母順序排列數組

int j; 
int b; 

for (int i = 0; i < 20 - 1; i++) { 
    int minIndex = i; 

    for (j = i + 1; j < 20; j++) { 
     b = (bookA[j].getTitle().compareTo(bookA[minIndex].getTitle())); 
     if (b < 0) { 
      minIndex=j; 
     } 
    } 

    Book temp = bookA[i]; 
    bookA[i] = bookA[j]; 
    bookA[j] = temp; 
} 

for (int z = 0; z < 20; z++) 
    System.out.println(bookA[z].toString()); 

回答

0

您在使用j作爲bookA[i] = bookA[j];的索引。問題在於,你在每次迭代中都覆蓋了j的值,所以當它最終到達bookA[i] = bookA[j];時,它總是會是20

你想要的是用bookA[minIndex]來代替它。生成的代碼如下所示:

int j; 
int b; 

for(int i=0;i<20-1;i++){ 
    int minIndex=i; 

    for(j=i+1;j<20; j++) { 
     b=(bookA[j].getTitle().compareTo(bookA[minIndex].getTitle())); 
     if(b<0){ 
      minIndex=j; 
     } 
    } 

    Book temp = bookA[i]; 
    bookA[i] = bookA[minIndex]; 
    bookA[minIndex] = temp; 
} 

for(int z=0;z<20;z++) 
    System.out.println(bookA[z].toString());