冒泡排序

来源:互联网 发布:python核心编程第三版 编辑:程序博客网 时间:2024/06/09 20:28
public class BubbleSort {    private int[] array;    private int count;    public BubbleSort(int[] array) {        this.array = array;    }    /**     * 冒泡排序就是拿一个数和剩下的数比较找出最小的,     * 再用同样的方式找出第二小的,     * 最大比较次数为 n*(n-1)/2     */    public void sortMin2Max() {        int length = array.length;        if (length > 0) {            // 拿n-1个数出来,最后一个不用比较            for (int i = 0; i < length - 1; i++) {                // 每个数都要跟他后面的数进行比较,所以j的开始位置是i+1                for (int j = i + 1; j < length; j++) {                    // 拿第i个数和第j个数进行比较                    if (array[i] > array[j]) {                        int temp = array[j];                        array[j] = array[i];                        array[i] = temp;                        count++;                    }                }            }        }        System.out.println("比较的次数:" + count);    }    /**     * 从大到小只要改变一下判断条件就行了     */    public void sortMax2Min() {        int length = array.length;        if (length > 0) {            for (int i = 0; i < length - 1; i++) {                for (int j = i + 1; j < length; j++) {                    if (array[i] < array[j]) {                        int temp = array[j];                        array[j] = array[i];                        array[i] = temp;                        count++;                    }                }            }        }        System.out.println("比较的次数:" + count);    }}


输出看看

public class Client {    public static void main(String[] args) {        int[] array = {3, 9, 5, 6, 1, 2, 6, 7, 0};        BubbleSort sort = new BubbleSort(array);        System.out.println("从大到小排序:");        sort.sortMax2Min();        print(array);        System.out.println("\n从小到大排序:");        sort.sortMin2Max();        print(array);    }    private static void print(int[] array) {        for (int i = 0; i < array.length; i++) {            System.out.print(array[i] + "   ");        }    }}

从大到小排序:
比较的次数:14
9   7   6   6   5   3   2   1   0   
从小到大排序:
比较的次数:44
0   1   2   3   5   6   6   7   9   

原创粉丝点击