为什么这个插入排序给了我错误的答案,而当我按照注释行指定的方式做时却得到了正确的答案?有什么区别?
public class Solution
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int i,j,n,sk=0; //consider another variable k
int a[]=new int[20];
n=s.nextInt();
for(i=0;i<n;i++)
a[i]=s.nextInt();
for(i=1;i<n;i++)
{ j=i-1;
//adding k=a[i]
while((j>=0)&&a[j]>a[i]) //a[j]>k instead of the condition a[j]>a[i]
{ sk++;
a[j+1]=a[j];
j--;
}
a[j+1]=a[i];
//a[j+1]=k instead of the previous line.
}
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}
最佳答案
这一行a[j+1]=a[j];
当 i = 1、j = 0 时,考虑数组 = {5,2,3},
while((j>=0)&&a[j]>a[i]) //a[j]>k instead of the condition a[j]>a[i]
{ sk++;
a[j+1]=a[j]; // a[1] = a[0]
j--; // j becomes -1 out of the loop
}
// Array becomes {5,5,3} after while loop, we lost 2
a[j+1]=a[i]; // again a[0] is just getting initialized to a[1]
//which are same
//a[j+1]=k instead of the previous line. **// K will have previous
a[1]**
}
当你执行 a[j+1]=a[j] 时,你已经更新了 a[1],然后在 while 循环之外你再次分配 a[1] = a[1],但是,k 将存储之前的值a[1] 值,不是更新后的值
关于java - 为什么这种插入排序方法会给出错误的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742348/