简体   繁体   English

使用2个数组的Java进行插入排序

[英]insertion sort using 2 arrays java

I am trying to figure out how to use insertion sort to sort an array of ints. 我试图弄清楚如何使用插入排序对整数数组进行排序。 I need to take values from the original array and put them into the new array. 我需要从原始数组中获取值并将其放入新数组中。 I will show what code I have, but I have hit a brick wall and cannot figure out how this sorting method works.` 我将显示我拥有的代码,但是我碰到了砖墙,无法弄清楚这种排序方法是如何工作的。

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));
}

The output is: 输出为:

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

When looking at Insertion Sort , first consider the algorithm - 查看插入排序时 ,首先考虑算法-

插入排序动画示例

From the animation, you should be able to tell that it's in-place. 从动画中,您应该能够知道它就位。 With that in mind, I think you wanted something like this - 考虑到这一点,我认为您想要这样的东西-

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));

Which outputs, 哪个输出,

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

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

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