给定数组[5 3 1 9 8 2 4 7],假设l = 0。
我将其转换为代码:
public class Test {
public static void main(String[] args) {
int[] a = {5,3,1,9,8,2,4,7};
int l = 0;
int p = a[l];
int i=l;
int j = 8;
do{
do{
i++;
System.out.println("Value of i " + i);
}while(a[i]>=p);
do{
j--;
System.out.println("\nValue of j " + j);
}while(a[j]<p);
swap(a,i,j);
System.out.println("\nSwapped! a[i] = " + a[i] + " a[j] = " + a[j]);
System.out.println("Swap 1");
for(int k : a){
System.out.print(k + " ");
}
}while(i>=j);
if(i>=j){
swap(a,i,j);
System.out.println("\nSwapped! a[i] = " + a[i] + " a[j] = " + a[j]);
System.out.println("Swap 2");
for(int k : a){
System.out.print(k + " ");
}
}
else{
swap(a,i,j);
System.out.println("\nSwapped! a[i] = " + a[i] + " a[j] = " + a[j]);
System.out.println("Swap 3");
for(int k : a){
System.out.print(k + " ");
}
swap(a,l,j);
System.out.println("\nSwapped! a[l] = " + a[l] + " a[j] = " + a[j]);
System.out.println("Swap 4");
for(int k : a){
System.out.print(k + " ");
}
}
System.out.println("\nreturn value is: " + j);
System.out.println("Final array: ");
for(int k : a){
System.out.print(k + " ");
}
}
public static void swap(int a[], int a1, int a2){
int temp = a[a1];
a[a1] = a[a2];
a[a2] = temp;
}
}
结果是:
但是当我用纸模拟它时,我的结果是不同的。不管怎么说,我误解了#34;重复直到&#34; &#34; do while&#34;或者我在纸上错误地分析了。
与我分享您的模拟队友:)谢谢!
答案 0 :(得分:2)
我错误地
repeat
until
do
while
或我在论文中错误地分析过。
您确实错误地翻译了repeat
/ until
。
The construct comes from Pascal-like languages.它类似于do
/ while
,但条件的含义完全相反:在do
/ while
条件下结束是延续条件,但在repeat
/ until
条件是终止条件。
此问题的解决方法是反转repeat
/ until
循环的条件:
do{
i++;
System.out.println("Value of i " + i);
} while(a[i]< p);
// ^