【问题标题】:Insertion Sort with two arrays两个数组的插入排序
【发布时间】:2019-03-24 16:44:45
【问题描述】:

我需要实现插入排序,但我必须使用另一个名为 temp 的数组。在这个数组中,必须将起始数组的值复制到正确的位置

我尝试通过一些我认为可以完成任务的修改来实现插入排序算法

public static void insertionSort(int[] a) {
    int[] temp = new int[a.length];
    for(int indice = 0; indice < a.length; indice++) {
        int key = a[indice];
        int j = indice - 1;

        while(j>=0 && a[j] > key) {
            a[j+1] = a[j];
            j = j-1;
        }
        a[j+1] = temp[j+1];
    }
}

我尝试将它与具有以下数字的数组一起使用:5、1、4、14、21、144、3 但是打印出来的是 0 0 0 0 0 0 0

【问题讨论】:

  • 你用temp做什么?
  • 我使用 temp 作为第二个数组,以正确的顺序将值放入其中
  • 不,你没有。这就是我问这个问题的原因,让你检查你的代码。
  • 如果要插入排序,实现插入排序。请参阅 Wikipedia、en.wikipedia.org/wiki/Insertion_sort 或其他任何地方的算法。 int[] temp 不存在。
  • 或者,如果您想返回输入数组的有序副本:1) 确保在任何地方都使用 temp,除非您在开头创建副本 2) 也返回它 (返回void 不会完成这项工作)。

标签: java insertion-sort


【解决方案1】:

问题是您正在创建临时数组,但您没有为任何位置分配任何值。因此,当您执行“a[j+1] = temp[j+1];”时该数组中没有任何内容,因此它将 0 分配给 a[j+1]。

如果我猜对了,temp 必须是 a 的副本,因此您可以执行以下操作:

int[] temp = new int[a.length]; 

for (int i = 0; i < temp.length; i++) 
{ 
    temp[i] = a[i];
}

【讨论】:

  • 在 temp 初始化之后。假设您希望 temp 成为 a 的副本
  • 现在您的代码可以完美运行。非常感谢您的帮助!
  • 别忘了用答案将此问题标记为已解决,这真的很有帮助。
【解决方案2】:

您没有使用临时数组。没有对 temp 进行分配。它有空数组。

在下面尝试,应该根据需要对数组进行排序

 public static void main(String[] args) {

        int[] a = { 5, 1, 4, 14, 21, 144, 3 };

        int[] arr2 = insertionSort(a);
        for(int i:arr2){
            System.out.print(i);
            System.out.print(", ");
        }
    }

 public static int[] insertionSort(int[] input){    
         int temp;
         for (int i = 1; i < input.length; i++) {
             for(int j = i ; j > 0 ; j--){
                 if(input[j] < input[j-1]){
                     temp = input[j];
                     input[j] = input[j-1];
                        input[j-1] = temp;
                    }
                }
            }
            return input;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    相关资源
    最近更新 更多