插入排序 - 降序

Lea*_*ner 2 java sorting algorithm insertion-sort

对不起,如果是一个基本问题...

我只是想了解更多关于算法的知识......

我编写了一个简单的代码来按升序执行插入排序,但由于某种原因,我无法按降序执行排序.

我尝试更改比较键(while(i> 0 && a [i]>键)到(i> 0 && a [i] <键))..它似乎部分工作但第一个元素没有被排序,我得到以下结果..有人让我知道我哪里错了吗?

1 11 10 9 5 4 3 2

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]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*her 9

你从来没有接触a[0]

while (i > 0 && a[i] < key) {
Run Code Online (Sandbox Code Playgroud)

所以它没有分类到它应有的位置.使用>=而不是>:

while (i >= 0 && a[i] < key) {
Run Code Online (Sandbox Code Playgroud)

按升序排序时会出现同样的问题.