为什么在Java中使用另一个数组值时不能使用数组索引减少?

huangapple go评论76阅读模式
英文:

Why I cannot use array index decrement when using a another array value in Java?

问题

这是Java中用于插入排序的简单代码。我试图减少我的Java代码的行数。但是在这个问题上无法做到。我想知道为什么不能这样做。

我尝试过的代码(错误发生在第9行)

import java.util.Scanner;

public class InsertionSortModified {
    public static int[] insertionSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int temp = arr[i];
            int pos = i;
            while (pos > 0 && arr[pos-1] > temp)
                arr[pos--] = arr[pos-1];
            arr[pos] = temp;
        }
        return arr;
    }

    public static void main(String args[]) {
        Scanner scnr = new Scanner(System.in);
        int elementarr[] = new int[5];

        for (int j = 0; j < 5; j++)
            elementarr[j] = scnr.nextInt();
        
        elementarr = insertionSort(elementarr);
        for (int j = 0; j < elementarr.length; j++)
            System.out.print(elementarr[j] + " ");
    }
}

在命令窗口中显示的错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
        at InsertionSortModified.insertionSort(InsertionSortModified.java:9)
        at InsertionSortModified.main(InsertionSortModified.java:22)

当代码修改为如下时,程序可以正常运行(第8到11行)

            while (pos > 0 && arr[pos-1] > temp) {
                arr[pos] = arr[pos-1];
                pos--;
            }

为什么我不能使用

arr[pos--] = arr[pos-1];

英文:

This is a simple code for Insertion Sort in Java. I tried reducing the lines of my Java code. But it cannot be done with this issue. I want to know why it cannot be done.

Code that I have tried (error happens in line number 9)

import java.util.Scanner;

public class InsertionSortModified {
    public static int[] insertionSort(int[] arr) {
        for (int i = 1; i &lt; arr.length; i++) {
            int temp = arr[i];
            int pos = i;
            while (pos &gt; 0 &amp;&amp; arr[pos-1] &gt; temp)
                arr[pos--] = arr[pos-1];
            arr[pos] = temp;
        }
        return arr;
    }

    public static void main(String args[]) {
        Scanner scnr = new Scanner(System.in);
        int elementarr[] = new int[5];

        for (int j = 0; j &lt; 5; j++)
            elementarr[j] = scnr.nextInt();
        
        elementarr = insertionSort(elementarr);
        for (int j = 0; j &lt; elementarr.length; j++)
            System.out.print(elementarr[j] + &quot; &quot;);
    }
}

Error showing in the command window

Exception in thread &quot;main&quot; java.lang.ArrayIndexOutOfBoundsException: -1
        at InsertionSortModified.insertionSort(InsertionSortModified.java:9)
        at InsertionSortModified.main(InsertionSortModified.java:22)

Program is working when the code modified to like this. (Line number 8 to 11)

            while (pos &gt; 0 &amp;&amp; arr[pos-1] &gt; temp) {
                arr[pos] = arr[pos-1];
                pos--;
            }

Why I cannot use

arr[pos--] = arr[pos-1];

答案1

得分: 3

在尝试执行以下操作时,

arr[pos--] = arr[pos-1];

当变量 pos 的值为 1 时,它会将 pos 减小到 0,然后在对 pos 进行第二次使用时,你使得它变为 0 - 1

英文:

When you are trying to do

arr[pos--] = arr[pos-1];

and the value of pos is 1 then it decrements pos to 0, then in the second usage of pos you are making it 0 - 1

答案2

得分: 1

在线 9,您将计数器递减的顺序弄错了。正确的行是

`arr[pos] = arr[--pos];`

在这里,您正在交换 arr[pos] 中的当前值和 arr[pos-1] 中的值,因为您在使用计数器之前就将其减小了。之后,pos 值已经在正确的位置插入 'temp' 值。

英文:

In line 9 your decreasing the counter in the wrong order. The correct line is

`arr[pos] = arr[--pos];`

Here you're swapping the current value in arr[pos] for that in arr[pos-1] as you are decreasing the counter before using it. After, the pos value is already in the correct position to insert the 'temp' value

答案3

得分: 0

我已经找到问题所在。代码逐步执行如下。

第9行:

i == 2 时,pos == 2。在第9行的执行顺序如下:

  1. 在刚开始执行 while 循环时,arr[2] = arr[pos-1]
  2. 定位数组索引2。但在定位后,pos 减少为 pos == 1
  3. 然后行变成 arr[2] = arr[1-1],意味着 arr[2] = arr[0]
  4. 在此之后,while 循环仍然为真。
  5. 然后在刚开始执行第二次 while 循环时,arr[1] = arr[pos-1]
  6. 然后定位数组索引1。但在定位后,pos 减少为 pos == 0
  7. 然后行变成 arr[1] = arr[0-1],意味着 arr[1] = arr[-1]
  8. 因此在这里发生错误(ArrayIndexOutOfBounds)。

更正后的代码如下(第9行):

arr[pos--] = arr[pos];

或者

arr[pos] = arr[--pos];
英文:

I have found what the problem is. Step by step execution of the code is here.

Line number 9:

When i == 2, pos == 2. At the line 9 execution order is like this.

  1. At initially first execution if the while loop, arr[2] = arr[pos-1].
  2. Positioning the array index 2. But after positioning pos is decreasing to pos == 1.
  3. Then line becomes to this arr[2] = arr[1-1] means arr[2] = arr[0].
  4. After that still while loop is true.
  5. Then the second execution of the while loop at initially arr[1] = arr[pos-1].
  6. Then positioning the array index 1. But after positioning pos is decreasing to pos == 0.
  7. Then line becomes to this arr[1] = arr[0-1] means arr[1] = arr[-1].
  8. So error happens in here. (ArrayIndexOutOfBounds).

Corrected code is like this. (Line number 9)

arr[pos--] = arr[pos];

or

arr[pos] = arr[--pos];

huangapple
  • 本文由 发表于 2020年10月2日 14:36:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64167084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定