【问题标题】:insertion sort using 2 arrays java使用2个数组java的插入排序
【发布时间】:2026-01-12 13:05:01
【问题描述】:

我试图弄清楚如何使用插入排序来对整数数组进行排序。我需要从原始数组中获取值并将它们放入新数组中。我将展示我拥有的代码,但是我碰壁了,无法弄清楚这种排序方法是如何工作的。`

import java.util.Arrays;
public static void main(String[] args)
{
int[] orgArray = {5,4,1,6,3,144,2,14};
    int[] newArray = new int[orgArray.length];
    int currentNum=0;
    for(int x=1; x<orgArray.length; x++)
    {
        if(x==1)
            newArray[0]=orgArray[0];
        else
            for(int y=x;y>0; y--)
            {
                currentNum = orgArray[x];
                if(newArray[y]<currentNum)
                {
                    for(int z=orgArray.length-2;z>y;z--)
                        newArray[z]=newArray[z+1];
                    newArray[x]=orgArray[x];
                }

            }
    }
    System.out.println("Ascending order : " + Arrays.toString(newArray));
}

输出是:

Ascending order : [5, 0, 14, 14, 14, 14, 14, 14]

【问题讨论】:

  • 前几天我在 python 中做了这个,即使那很痛苦:/
  • 一定要用两个数组吗?
  • 显然去年的班级很容易获得了这个项目,但对我来说,这是一个为期 3 天的项目,直到 @Elliot_Frisch 提供帮助。

标签: java arrays sorting insertion-sort


【解决方案1】:

Insertion Sort时,先考虑算法-

从动画中,您应该能够看出它是就地的。考虑到这一点,我认为您想要这样的东西 -

int[] orgArray = { 5, 4, 1, 6, 3, 144, 2, 14 };
int[] newArray = new int[orgArray.length];
// Copy the original array.
System.arraycopy(orgArray, 0, newArray, 0,
    orgArray.length);
for (int x = 1; x < newArray.length; x++) {
  int currentNum = newArray[x]; // <-- the current number changes on every loop
  int y = x;

  // The actual condition on which to shift up!
  for (; y > 0 && newArray[y - 1] > currentNum; y--) {
    newArray[y] = newArray[y - 1];
  }
  // All shifts done, insert the correct place.
  newArray[y] = currentNum;
}
System.out.println("Ascending order : "
    + Arrays.toString(newArray));

哪些输出,

Ascending order : [1, 2, 3, 4, 5, 6, 14, 144]

【讨论】:

  • 我会赞成您的评论,但我没有足够的声誉。我不知道 System.arraycopy();存在。感谢您的帮助!