简体   繁体   English

数组后面的Java插入排序算法

[英]Java insertion sort algorithm from the back of the array

So I have been trying to write the insertion sort algorithm so that the values are inserted towards the back of the array rather than the front (putting the largest values towards the back rather than the smallest towards the front) and I have been having trouble seeing if I am doing it right. 因此,我一直在尝试编写插入排序算法,以便将值插入到数组的后面而不是前面(将最大的值放在后面而不是最小的值放在前面),而我一直很难看到如果我做对了。 If someone can tell me if I have the right idea, that'd be great. 如果有人可以告诉我我是否有正确的主意,那就太好了。 Here is my code, it doesn't seem to work as I want it to: 这是我的代码,它似乎无法正常运行:

public static void insertionSort(Comparable[] item, int size) {
    for (int k = size - 1; k > 0; k--)
        insertInOrder(item, k);
}

private static void insertInOrder(Comparable[] item, int m) {
    Comparable save = item[m];
    for (; m > 0 && item[m-1].compareTo(save) > 0; m--)
        item[m] = item[m - 1];
    item[m] = save;
}

There are two problems with your code. 您的代码有两个问题。 Here is a fixed version: 这是固定版本:

public static void insertionSort(Comparable[] item, int size) {
    // Changed to k >= 0, otherwise we would have ignored the 0th
    // element and not move it to higher positions in the array
    for (int k = size - 1; k >= 0; k--)
        insertInOrder(item, k, size);
}

// Added size as a parameter
private static void insertInOrder(Comparable[] item, int m, int size) {
    Comparable save = item[m];
    // This loop needs to count upward, because you
    // want to move large values towards the back
    for (; m + 1 < size && item[m+1].compareTo(save) < 0; m++)
        item[m] = item[m + 1];
    item[m] = save;
}

Additional notes: 补充笔记:

  • Normally we pluralize the name of an array, ie: Comparable[] items . 通常,我们将数组的名称复数,即: Comparable[] items
  • Consider using generics for the Comparable type. 考虑对Comparable类型使用泛型。
  • Ask your question next time on Code Review Stack Exchange . 下次在Code Review Stack Exchange上提问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM