开发者社区> 问答> 正文

冒泡法排序,java代码 排序1 8 5 2 4 9

冒泡法排序,java代码 排序1 8 5 2 4 9

展开
收起
知与谁同 2018-07-18 11:52:52 1765 0
2 条回答
写回答
取消 提交回答
  • public class BubbleTest

    {

    int[] array = new int[]{1,8,5,2,4,9};

    public void test()

    {

    for(int i = 0; i < array.length; i++)

    {

    for(int j = 0; j < array.length - 1; j++)

    {

    /*

    * 从大到小排

    */

    int temp;

    if(array[j] < array[j+1])

    {

    temp = array[j];

    array[j] = array[j+1];

    array[j+1] = temp;

    }

    /*

    * 从小到大排序

    * if(array[j] > array[j+1])

    {

    temp = array[j];

    array[j] = array[j+1];

    array[j+1] = temp;

    }*/

    }

    }

    for(int i = 0; i < array.length; i++)

    {

    System.out.print(array[i]+"--");

    }

    }

    public static void main(String[] args)

    {

    BubbleTest b = new BubbleTest();

    b.test();

    }

    }

    2019-07-17 22:50:55
    赞同 展开评论 打赏
  • 12535
    public class Test {
    public static void main(String[] args) {
    int[] a = {1, 8, 5, 2, 4, 9};
    //冒泡排序
    for (int k = 0; k < a.length - 1; k++) {
    for (int j = k + 1; j < a.length; j++) { // 升序把<改成>
    if (a[k] > a[j]) {
    int temp = a[k];
    a[k] = a[j];
    a[j] = temp;
    }
    }
    }
    System.out.println("排序后: ");
    for(int i = 0; i < a.length; i++){
    System.out.print(a[i] + "  ");
    }
    }
    }

    2019-07-17 22:50:55
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载