【问题标题】:How to correct insertion sort?如何纠正插入排序?
【发布时间】:2013-05-16 14:36:48
【问题描述】:

这是我的第一个插入数组,但它可能没有排序,我不确定我哪里出错了。有什么想法吗?

  for (int i=1; i<array.length; i++) {
            int temp = array[i];
            for (int j=i-1; j >=0 && temp < array[j]; j--) {
                array[j+1] = array[j];
                array[j+1] = temp;
            }
            ItsATextArea.append(array[i] + "\n");
        }

【问题讨论】:

    标签: java arrays sorting loops insertion-sort


    【解决方案1】:

    我认为你在这里犯了错误

    array[j+1] = array[j];
    array[j+1] = temp;  // It must be array[j] = temp
    

    【讨论】:

    • 你确定吗?我在答案中看到的没有任何区别,没有排序。
    【解决方案2】:

    你几乎是对的。 '数组[j + 1] = temp;'行应该在循环之外。

            for (int i=1; i<array.length; i++) {
                int temp = array[i];
                int j = i - 1;
                for (; j >=0 && temp < array[j]; j--) {
                    array[j+1] = array[j];
                }                   
                array[j+1] = temp;
            } 
    

    另外,如果您打算打印排序后的数组,请在算法完成后进行。因为你不能真正知道插入的元素“temp”是否在正确的位置,但在你添加“append”行的地方。例如,如果原始数组中的最后一个元素是最小的,则所有元素都需要向右移动一个位置。

    【讨论】:

      【解决方案3】:
      array[j+1] = array[j];
      array[j+1] = temp;
      

      对我来说看起来有问题。您确定要在数组中使用相同的元素两次吗?

      【讨论】:

        猜你喜欢
        • 2015-05-25
        • 2021-01-09
        • 1970-01-01
        • 1970-01-01
        • 2020-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多