Java 使用插入排序进行降序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23315306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:49:24  来源:igfitidea点击:

Using insertion sort for descending order?

javasorting

提问by user3566347

I am trying to learn how to use Insertion Sort, and this is the main code I'm using:

我正在尝试学习如何使用插入排序,这是我使用的主要代码:

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
 }

However, I've tried to change the - to + to try to change the output to descending order, but I'm confusing myself even more.

但是,我尝试将 - 更改为 + 以尝试将输出更改为降序,但我更加困惑。

This is the complete code I'm using:

这是我正在使用的完整代码:

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

Thanks for any help and suggestions

感谢您的任何帮助和建议

采纳答案by lealand

To sort in descending order, you only need to change the comparison:

要按降序排序,您只需要更改比较:

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

Note the <instead of >.

请注意<代替>