在java中使用boolean冒泡。

时间:2014-02-08 00:08:21

标签: java for-loop while-loop boolean bubble-sort

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循环中的代码。该代码假设连续排序,直到它将数组中的数字从最小到最大组织。然而,我真的迷路了,我似乎无法弄清楚我哪里出错了。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

问题在于您的切换算法。您要分配两次临时温度。

 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]);
        }
    }
}

答案 1 :(得分:0)

这个工作

 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;
    }


}