排序——交换排序之冒泡排序

来源:互联网 发布:windows 文件管理工具 编辑:程序博客网 时间:2024/05/21 10:25

冒泡排序(BubbleSort)算法描述:

比较相邻两个元素的大小,如果反序(相等也算)则交换;若按冒泡排序(升序)排序,每一趟将序列中最大的元素依次交换到最后的位置。


代码实现如下:

package g;

public class BubbleSort {
    public static int[] randomInt(int n, int size) {
        int[] value = new int[n];
        for (int i = 0; i < value.length; i++) {
            value[i] = (int) (Math.random() * size);
        }
        return value;
    }

    public static void print(int[] value) {
        for (int i : value) {
            System.out.print(i + " ");
        }
    }

    // 交换元素keys[i]与keys[j],i、j的范围由调用者控制
    private static void swap(int[] keys, int i, int j) {
        int temp = keys[j];
        keys[j] = keys[i];
        keys[i] = temp;
    }

    // 冒泡排序(升序)--->默认的排序
    public static void bubbleSort(int[] keys) {
        bubbleSort(keys, true);
    }

    // 重载方法bubbleSort
    public static void bubbleSort(int[] keys, boolean asc) {
        // 若asc为true,为升序排列,否则为降序排列
        System.out.println("\n冒泡排序(" + (asc ? "升" : "降") + ")序:");
        // 是否交换的标记,asc为true时交换
        boolean exchange = true;
        // 有交换时在进行下一趟,最多n-1趟
        for (int i = 1; i < keys.length && exchange; i++) {
            // 若没有交换
            exchange = false;
            // 一趟比较、交换
            for (int j = 0; j < keys.length - i; j++) {
                // 相邻元素比较,若反序,则交换
                if (asc ? keys[j] > keys[j + 1] : keys[j] < keys[j + 1]) {
                    swap(keys, j, j + 1);
                    // 有交换
                    exchange = true;
                }

            }
            System.out.print("第" + i + "趟:\t");
            print(keys);
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[] keys = BubbleSort.randomInt(10, 100);
        System.out.print("关键字:");
        BubbleSort.print(keys);
        BubbleSort.bubbleSort(keys);
    }
}
输出如下:

关键字:92 93 85 43 77 15 78 77 93 35
冒泡排序(升)序:
第1趟:    92 85 43 77 15 78 77 93 35 93
第2趟:    85 43 77 15 78 77 92 35 93 93
第3趟:    43 77 15 78 77 85 35 92 93 93
第4趟:    43 15 77 77 78 35 85 92 93 93
第5趟:    15 43 77 77 35 78 85 92 93 93
第6趟:    15 43 77 35 77 78 85 92 93 93
第7趟:    15 43 35 77 77 78 85 92 93 93
第8趟:    15 35 43 77 77 78 85 92 93 93
第9趟:    15 35 43 77 77 78 85 92 93 93


0 0
原创粉丝点击