冒泡排序

从小到大

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
        // 排序前:
        System.out.println(Arrays.toString(ns));
        for (int i = 0; i < ns.length - 1; i++) {
            for (int j = 0; j < ns.length - i - 1; j++) {
                if (ns[j] > ns[j+1]) {
                    // 交换ns[j]和ns[j+1]:
                    int tmp = ns[j];
                    ns[j] = ns[j+1];
                    ns[j+1] = tmp;
                }
            }
        }
        // 排序后:
        System.out.println(Arrays.toString(ns));
    }
}

从大到小

public class Main {
    public static void main(String[] args) {
        int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
        System.out.println(Arrays.toString(ns));
        int tmp;
        for(int i=0;i<ns.length;i++)
        {
            for(int j=i;j<ns.length;j++)
            {
                if(ns[j]>ns[i])
                {
                    tmp=ns[i];
                    ns[i]=ns[j];
                    ns[j]=tmp;
                }
            }
        }
        System.out.println(Arrays.toString(ns));
        if (Arrays.toString(ns).equals("[96, 89, 73, 65, 50, 36, 28, 18, 12, 8]")) {
            System.out.println("测试成功");
        } else {
            System.out.println("测试失败");
        }
    }
}

Arrays.sort()

JDK自带排序函数

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
        Arrays.sort(ns);
        System.out.println(Arrays.toString(ns));       //[8, 12, 18, 28, 36, 50, 65, 73, 89, 96]
    }
}

如果对一个字符串数组进行排序

String[] ns = { "banana", "apple", "pear" };
//apple banana pear
THE END
最后修改:2020 年 03 月 05 日 15 : 37
本文链接:https://www.j000e.com/%E6%95%B0%E7%BB%84%E6%93%8D%E4%BD%9C/Sortinganarray.html
版权声明:本文『[数组排序][冒泡排序][Arrays.sort()]』为『Joe』原创。著作权归作者所有。
转载说明:[数组排序][冒泡排序][Arrays.sort()] || Joe's Blog』转载许可类型见文末右下角标识。允许规范转载时,转载文章需注明原文出处及地址。
Last modification:March 5, 2020
If you think my article is useful to you, please feel free to appreciate