英文:
I was practicing insertion sort in java, but as soon as I replaced the j+1 from ++j in the inner loop it got stucked over there
问题
当我将 j+1 替换为 ++j 时,它陷入了一个无限循环,既不增加也不减少。
public class InsertionSort {
public static void main(String[] args) {
int[] arr= {5,7,6,4,8,9,3,1,2};
int n = arr.length;
for(int i = 1 ; i < n ; i++) {
int j = i-1;
int key = arr[i];
while(j>=0 && key<arr[j]) {
arr[j+1]=arr[j--]; // ***工作正常***
}
arr[++j]=key;
}
for (int i : arr) {
System.out.print(i+" ");
}
}
}
在以下代码中陷入困境:
public class InsertionSort {
public static void main(String[] args) {
int[] arr= {5,7,6,4,8,9,3,1,2};
int n = arr.length;
for(int i = 1 ; i < n ; i++) {
int j = i-1;
int key = arr[i];
while(j>=0 && key<arr[j]) {
arr[++j]=arr[j--]; // ***陷入困境***
}
arr[++j]=key;
}
for (int i : arr) {
System.out.print(i+" ");
}
}
}
英文:
When I replaced j+1 with ++j it got stuck over there with an infinite loop neither incrementing nor decrementing
public class InsertionSort {
public static void main(String[] args) {
int[] arr= {5,7,6,4,8,9,3,1,2};
int n = arr.length;
for(int i = 1 ; i < n ; i++) {
int j = i-1;
int key = arr[i];
while(j>=0&&key<arr[j]) {
arr[j+1]=arr[j--]; // ***Working Fine***
}
arr[++j]=key;
}
for (int i : arr) {
System.out.print(i+" ");
}
}
}
Getting stucked in the below code
public class InsertionSort {
public static void main(String[] args) {
int[] arr= {5,7,6,4,8,9,3,1,2};
int n = arr.length;
for(int i = 1 ; i < n ; i++) {
int j = i-1;
int key = arr[i];
while(j>=0&&key<arr[j]) {
arr[++j]=arr[j--];// ***Stucked***
}
arr[++j]=key;
}
for (int i : arr) {
System.out.print(i+" ");
}
}
}
答案1
得分: 1
这是要无限循环的。在第一个 j+1 的示例中,当执行 j+1 时,并未对 j 的值进行增加。
while(j>=0 && key<arr[j]) {
arr[j+1]=arr[j--]; // j 的值没有增加,实际上是通过 j-- 进行了减少。
}
在第二个 ++j 的示例中,执行了两个操作。
操作 1:
arr[++j] // 这个操作增加了 j 的值
操作 2:
arr[j--] // 这个操作减少了 j 的值
在同一行中,你在增加和减少 j 的值。因此,j 的值永远不会为 0,它陷入了无限循环。希望这能澄清问题。
英文:
This is meant to be stuck infinitely.
In the first example of j+1, the value of j is not incremented when you do j+1.
while(j>=0&&key<arr[j]) {
arr[j+1]=arr[j--]; // value of J is not incremented, it's actually decremented by j--.
}
In the second example of ++j, there are two operations being performed.
Operation 1:
arr[++j] // This operation increments the value of j
Operation 2:
arr[j--] // This operation decrements the value of j
In the same line, you are incrementing and decrementing the value of j. Hence the value of j is never 0 and it's stuck in an infinite loop.
Hope this clarifies the issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论