Java 带插入排序的变量赋值问题

Java 带插入排序的变量赋值问题,java,Java,在下面实现插入排序的代码中,当用nums[i]替换currentElement时(在第二个for循环中),它会完全中断。据我所知,i直到下一次迭代才改变。即使在第二个for循环中打印i和currentElement,也表明它们始终是相同的 使用nums[i]时出现了什么问题 public class InsertionSort { 4 public static void main(String[] args){ 5 int[] nums

在下面实现插入排序的代码中,当用
nums[i]
替换
currentElement
时(在第二个for循环中),它会完全中断。据我所知,
i
直到下一次迭代才改变。即使在第二个for循环中打印
i
currentElement
,也表明它们始终是相同的

使用
nums[i]
时出现了什么问题

public class InsertionSort {
  4         public static void main(String[] args){
  5                 int[] nums = {23,4,5234,1234,3,2,0,-44, -1239};
  6                 sort(nums);
  7                 
  8                 for (int i : nums) {
  9                         System.out.println(i);
 10                 }
 11                 
 12         }
 13
 14
 15         public static void sort(int[] nums) {
 16                 for (int i = 1; i < nums.length; i++) {
 17                         int currentElement = nums[i];
 18                         int j;
 19                         for (j = i - 1; j >= 0 && nums[j] > currentElement; j--) {
 20                                 nums[j + 1] = nums[j];
 21                         }
 22                         nums[j + 1] = currentElement;
 23                 }
 24         }
 25 }
公共类插入排序{
4公共静态void main(字符串[]参数){
5 int[]nums={23,452341234,3,2,0,-44,-1239};
6类(nums);
7.
8用于(int i:nums){
9系统输出打印Ln(i);
10                 }
11
12         }
13
14
15公共静态无效排序(int[]nums){
16表示(int i=1;i=0&&nums[j]>currentElement;j--){
20努姆[j+1]=努姆[j];
21                         }
22 nums[j+1]=电流元件;
23                 }
24         }
25 }
如果这很重要,则结果会按照
currentElement
自然排序,使用
nums[i]
时就是这样排序的:
4、23、1234、3、2、0、-44、-1239、5234。

最内层循环所做的第一件事就是改变
nums[j+1]
;由于
j=i-1
,这意味着它正在改变
nums[i]