java学习23

39 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第23天,点击查看活动详情

冒泡排序

基本思路

冒泡排序:重复地扫描待排序列,并比较两个相邻的元素,如果顺序错误就把他们交换过来。一直重复这样的过程,直到没有任何相邻元素交换即可结束。每一次冒泡排序,都会确定一个数的最终位置,如下图手动模拟了冒泡排序的过程

image.png

代码实现

其实冒泡排码我们应该都很熟悉,双循环中外层循环是冒泡排序需要进行的趟数,内循环是对每一趟排序,比较相邻元素,而在内循环中,只需要循环到未决定位置的数据。

我觉得冒泡排序中间的核心代码三行:交换数据,在写代码中会经常用到,用一个临时变量作为中介,交换两个数据。

    /**
     * Bubble sort.
     *
     */
    public void bubbleSort() {
        boolean tempSwapped;
        DataNode tempNode;
        //几趟冒泡排序
        for (int i = length - 1; i > 1; i--) {
            tempSwapped = false;
            //比较相邻元素之间的数据
            for (int j = 0; j < i; j++) {
                if (data[j].key > data[j + 1].key) {
                    // Swap.
                    tempNode = data[j + 1];
                    data[j + 1] = data[j];
                    data[j] = tempNode;
 
                    tempSwapped = true;
                }
            }
 
            // No swap in this round. The data are already sorted.
            if (!tempSwapped) {
                System.out.println("Premature");
                break;
            }
 
            System.out.println("Round " + (length - i));
            System.out.println(this);
        }
    }

测试结果

-------bubbleSortTest-------
I am a data array with 7 items.
(1, if)  (3, then)  (6, else)  (10, switch)  (7, case)  (5, for)  (9, while)  
Round 1
I am a data array with 7 items.
(1, if)  (3, then)  (6, else)  (7, case)  (5, for)  (9, while)  (10, switch)  
Round 2
I am a data array with 7 items.
(1, if)  (3, then)  (6, else)  (5, for)  (7, case)  (9, while)  (10, switch)  
Round 3
I am a data array with 7 items.
(1, if)  (3, then)  (5, for)  (6, else)  (7, case)  (9, while)  (10, switch)  
Premature
Result
I am a data array with 7 items.
(1, if)  (3, then)  (5, for)  (6, else)  (7, case)  (9, while)  (10, switch)

总结

今天学习的冒泡排序,虽然冒泡排序很简单,但我觉得其代码实现挺重要的,在很多其他排序中会用到交换两个数据这个思路,而大部分的思想都会借助一个临时变量做中介。