簡體   English   中英

使用插入排序降序?

[英]Using insertion sort for descending order?

我正在嘗試學習如何使用插入排序,這是我正在使用的主要代碼:

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);
        }
    }
}

感謝您的幫助和建議

要以降序排序,您只需要更改比較:

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

請注意<而不是>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM