2014-04-26 45 views
0

我想学习如何使用插入排序,这是我使用的主要代码:使用插入排序降序?

for (j = 1; j < num.length; j++) // Start with 1 (not 0) 
{ 
    key = num[ j ]; 
    for(i = j - 1; (i >= 0) && (num[ i ] < key); i--) // Smaller values are moving up 
    { 
     num[ i+1 ] = num[ i ]; 
    } 
    num[ i+1 ] = key; // Put the key in its proper location 
} 

不过,我试图改变 - 到+,试图改变输出到降序,但我更迷惑自己。

这是我使用的完整代码:

public class InsertionSort { 

    public static void main(String[] args) { 
     int A[] = new int[10]; 
     populateArray(A); 
     System.out.println("Before Sorting: "); 
     printArray(A); 
     // sort the array 
     insertionSort(A); 
     System.out.println("\nAfter Sorting: "); 
     printArray(A); 
    } 

    /** 
    * This method will sort the integer array using insertion sort algorithm 
    */ 
    private static void insertionSort(int[] arr) { 
     for (int i = 1; i < arr.length; i++) { 
      int valueToSort = arr[i]; 
      int j = i; 
      while (j > 0 && arr[j - 1] > valueToSort) { 
       arr[j] = arr[j - 1]; 
       j--; 
      } 
      arr[j] = valueToSort; 
     } 
    } 

    public static void printArray(int[] B) { 
     System.out.println(Arrays.toString(B)); 
    } 

    public static void populateArray(int[] B) { 
     for (int i = 0; i < B.length; i++) { 
      B[i] = (int) (Math.random() * 100); 
     } 
    } 
} 

感谢所有帮助和建议

+0

您可以添加使用您的第一个代码块的'insertionSort'代码吗?我想更好地了解你错在哪里。 – lealand

回答

1

要按降序排列,你只需要改变比较:

while (j > 0 && arr[j - 1] < valueToSort) { 

注意<而不是>

+0

是的,如果'j-1'小一些,那么正确'valueToSort'在'j'处,然后将'j-1'移到较高索引处 - 在'j'按降序排序。 –