import java.util.*;
public class Zhangbubble
{
public static void main (String[] args)
{
int Bub[] = new int[6];
Random randy = new Random();
boolean Done = false;
for (int x=0; x<6; x++)
{
Bub[x] = randy.nextInt(100);
System.out.println (Bub[x]);
}
System.out.println ("This is the original array");
while (! Done)
{
Done = true;
for(int x = 0; x < Bub.length - 1; x++)
{
for(int j = x + 1; j < Bub.length; j++)
{
if(Bub[x] >Bub[j])
{
int temp = Bub[x];
Bub[x] = Bub[j];
Bub[j] = temp;
}
}
}
for(int x = 0; x < Bub.length; x++)
{
System.out.println(Bub[x]);
}
}
}
}
所以我的冒泡排序很好。至少我认为确实如此。但我想看看每个交换,我不知道如何编码。所以不是只打印原始数字和有序数字,有没有办法可以看到中间的所有数字顺序?所以在查看最终有序序列之前的数字顺序后,我发现数字没有切换他们想的方式。它不需要前两个数字,如果需要则交换它们,然后移动第二个数字。相反,它似乎跳了一下但仍然给出了正确的有序对。有人可以找出导致这种情况的原因吗?
答案 0 :(得分:0)
或类似的东西......?
if(Bub[x] >Bub[j])
{
System.out.println("Swapping value "+Bub[x]+" at index "+x);
System.out.println(" with value "+Bub[j]+" at index "+j);
...
}
答案 1 :(得分:0)
你可以这样打印:
System.out.print("[");
for(int xe = 0; xe<6; xe++) { System.out.print(Bub[xe]+" ");
System.out.println("]");
但我仍然建议你使用Debugger来做到这一点。然后,您可以逐行查看代码中所有变量的更改。