java - 使用插入排序降序?

标签 java sorting

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

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) {

注意 <而不是 > .

关于java - 使用插入排序降序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23315306/

相关文章:

javascript - 按两个不同的标准对数组中的对象进行排序

java - 按对象的属性按数字顺序对数组进行排序

java - 使用Docker构建一个Maven项目并提交为Flink作业

java - 参数中的不兼容类型

java - 如何检查 Swing 中的文本是否被选中?

c# - 在datagridview中对数字列进行排序

javascript - 在 JavaScript 中按对象的属性值排序?

javascript - 简单的名称排序算法 - Javascript

java - 如何将MySQL数据库中的数据导出为特定格式的.flr或.pl文件

java - 编写一个名为的递归方法,该方法接受一个整数数组并以相反的排序顺序返回该数组