冒泡排序应用——数组排序

来源:互联网 发布:软件学校 编辑:程序博客网 时间:2024/06/05 03:18
/* * 冒泡排序应用——数组排序 *  * 题目描述: *  给定一个数组m[] = {49, 38, 65, 97, 76, 13, 27, 49}, *  将该数组中的元素按照从小到大的顺序排列 */public class BubbleSort {    public static void main(String[] args) {//      int[] m = {49, 38, 65, 97, 76, 13, 27, 49};        int[] m = {59, 63, 28, 46, 98, 32, 21, 10, 85, 66, 99};        BubbleSort.bubbleSort(m, m.length);        System.out.print("一般冒泡排序后的数组 m[]:");        BubbleSort.printArray(m);        System.out.println();        BubbleSort.bubbleSortBetter(m, m.length);        System.out.print("优化冒泡排序后的数组 m[]:");        BubbleSort.printArray(m);    }    /**     * 打印数组     *      * @param array:被打印的数组     */    public static void printArray(int array[]) {        for(int a: array) {            System.out.print(a + " ");        }    }    /**     * 一般冒泡排序算法     *      * @param array:被排序的数组     * @param n:被排序数组的长度     */    public static void bubbleSort(int array[], int n) {        int temp = 0;        //一定进行 n-1 轮比较        for(int i = 0; i < n-1; i++) {            //每一轮比较前 n-1-i 个元素,即已排序好的最后 i 个元素不用比较            for(int j = 0; j < n-1-i; j++) {                if(array[j] > array[j + 1]) {                    temp = array[j];                    array[j] = array[j+1];                    array[j+1] = temp;                }            }        }    }    /**     * 优化冒泡排序算法     *      * @param array:被排序的数组     * @param n:被排序数组的长度     */    public static void bubbleSortBetter(int array[],int n) {        int temp = 0;        //最多进行 n-1 轮比较        for(int i = 0; i < n-1; i++) {            Boolean isSorted = true;            //每一轮比较前 n-1-i 个元素,即已排序好的最后 i 个元素不用比较            for(int j = 0; j < n-1-i; j++) {                if(array[j] > array[j + 1]) {                    temp = array[j];                    array[j] = array[j+1];                    array[j+1] = temp;                }            }            //如果有一趟比较没有发生交换,说明数组已经排序好了            if(isSorted) break;         }    }}
0 0