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++)
{
if(Bub[x+1] > Bub[x])
{
int temp = Bub[x];
Bub[x] = Bub[x+1];
temp = Bub[x+1];
Done = false;
}
else
{
Done = false;
}
}
for(int x = 0; x<6; x++)
{
System.out.print(Bub[x]+" ");
}
}
}
}所以我的编程老师让我们用一个布尔值用java做一个泡泡排序。他的示例显示了带for循环的while循环中的代码。这段代码应该持续排序,直到数组中的数字从最少到最大。然而,我真的迷路了,我似乎不知道自己哪里出了问题。任何帮助都将不胜感激!
发布于 2014-02-08 00:20:34
问题在于你的切换算法。你要分配两次临时时间。
int temp = Bub[x];
Bub[x] = Bub[x+1];
temp = Bub[x+1]; //Here should assign Bub[x+1] to temp
//Example: Bub[x+1] = temp编辑-实际上,排序算法本身也有一些改进。就我个人而言,我喜欢这样做:
public class Sort {
private static int[] array = { 3, 8, -1, 7, 0, 3 };
public static void main(String[] args) {
for(int i = 0; i < array.length - 1; i++) {
for(int j = i + 1; j < array.length; j++) {
if(array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for(int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}发布于 2014-02-08 00:23:46
这工作
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)
{
for (int x = 0; x<Bub.length-1; x++)
{
if(Bub[x+1] > Bub[x])
{
int temp = Bub[x];
Bub[x] = Bub[x+1];
Bub[x+1]=temp ;
Done = false;
}
else
{
Done = false;
}
}
for(int x = 0; x<6; x++)
{
System.out.print(Bub[x]+" ");
}
Done = true;
}
}https://stackoverflow.com/questions/21640027
复制相似问题