为什么这个插入排序给了我错误的答案,而当我按照评论行指定的方式得到正确答案时?有什么区别?
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]);
}
}
答案 0 :(得分:3)
此行 a [j + 1] = a [j] ;
当i = 1,j = 0,
时,请考虑array = {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]**
}
当您执行[j + 1] = a [j]时已经更新了[1],然后在while循环之外再次分配[1] = a [1],但是k将存储之前的a [1]值,而不是更新的值
答案 1 :(得分:0)
为简单起见,在您的解决方案中,您通过引用编辑变量,而正确的解决方案是按值传递它们。
当您通过引用传递变量时,编辑一个值与编辑第二个值相同。
这是一个简单的代码,可以帮助您理解:
public class Main {
public static void main(String[] args) {
Foo foo = new Foo();
int valueToAdd = 5;
// foo.a will not be modified because we set the parameter by value
editTestByValue(foo.a, valueToAdd);
System.out.println(foo.a); // prints 1
editTestByReference(foo, valueToAdd);
// foo.a will be modified because we set the parameter by reference
System.out.println(foo.a); // prints 6
}
public static void editTestByValue(int a, int valueToAdd){
a += valueToAdd;
}
public static void editTestByReference(Foo foo, int valueToAdd){
foo.a += valueToAdd;
}
}
class Foo {
public int a = 1;
}
使用数组而不是类来使用相同的东西。
有关详细信息,请查看此信息 What's the difference between passing by reference vs. passing by value?
希望它有所帮助!