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]);
}
}
}
}所以我的冒泡排序工作得很好。至少我是这么认为的。但我希望看到每个交换,但我不确定如何编码。所以,有没有一种方法可以让我看到中间的所有数字顺序,而不是只打印出原始数字和有序数字呢?所以在查看了最终有序序列之前的数字顺序后,我发现这些数字并没有按预期的方式进行切换。它不需要前两个数字,如果需要的话,交换它们,然后移动到第二个数字对。相反,它似乎跳来跳去,但最终仍然给出了正确的有序对。有人能找出是什么原因造成的吗?
发布于 2014-02-08 09:34:44
或者像这样的东西...?
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);
...
}发布于 2014-02-08 10:32:58
您可以使用以下方式进行打印:
System.out.print("[");
for(int xe = 0; xe<6; xe++) { System.out.print(Bub[xe]+" ");
System.out.println("]");但我仍然建议您使用Debugger来完成此操作。然后,您可以逐行查看代码中所有变量的更改。
https://stackoverflow.com/questions/21640732
复制相似问题