2013-03-08 141 views
2

很抱歉,如果它的一個基本問題......插入排序 - 降序

我只是想了解更多關於算法...

我寫了一個簡單的代碼升序進行插入排序,但由於某種原因,我無法使其按降序執行排序。

我試圖改變對比密鑰(而(ⅰ> 0 & & A [1]>鍵)至(i> 0 & & A [1] <鍵))..它似乎部分地工作,但在第一元素沒有得到排序,我得到了下面的結果..有人讓我知道我錯在哪裏?

public class InsertionSort { 
    public static void main(String args[]) { 
     int[] a = { 1,10,11,5, 9, 3, 2, 4 }; 
     // Loop through the entire array length. Consider you already have one 
     // element in array, start comparing with 
     // first element 
     for (int j = 1; j < a.length; j++) { 
      // Get the key (The value that needs to be compared with existing 
      // values. 
      int key = a[j]; 
      // Get the array index for comparison, we need to compare with all 
      // other elements in the array with 
      // key 
      int i = j - 1; 
      // While i > 0 and when key is less than the value in the array 
      // shift the value and insert 
      // the value appropriately. 
      //System.out.println(j); 
      while (i > 0 && a[i] < key) { 
       a[i + 1] = a[i]; 
       i = i - 1; 
       a[i + 1] = key; 
      } 
     } 
     for (int k = 0; k < a.length; k++) { 
      System.out.println(a[k]); 
     } 
    } 
} 

回答

9

你永遠在

while (i > 0 && a[i] < key) { 

如此動人a[0]它沒有分到應有的位置。使用>=代替>:按升序排序時會發生

while (i >= 0 && a[i] < key) { 

同樣的問題。

+0

對不起..我的測試數據不好,我沒有意識到,當升序排列時,我沒有碰到數組中的第一個元素。 – Learner 2013-03-08 16:01:33

+1

不管怎麼樣,好的嘗試@學習者繼續努力工作。 – 2013-03-08 16:09:08

+0

如果我沒有錯,那麼a [i + 1] = key行不應該出自while循環嗎? – Azeem 2016-10-14 12:49:20

2

數組中的第一個元素是a[0]。你沒有在任何地方比較它。

1

從數組a []開始,從0開始到達第一個元素a [0]。因此,[j]中的第一個元素將是[0]而不是[1];