Java冒泡排序

來源:互聯網
上載者:User

標籤:迴圈   推薦   code   ring   分享   int   原理   代碼   技術   

說明:歡迎批評指正,留言點贊!如若轉載,請註明原文地址:http://www.cnblogs.com/chris0710/p/8995234.html

這篇文章將通過簡單例子說明冒泡排序原理,閑話少說,直接上代碼。

 1 /** 2  * 冒泡排序 3  * 4, 6, 2, 3, 5 4  * 思路:先寫內迴圈(遍曆次數: times = arr.length - 1),排好第一個數字,再添加外迴圈,排好所有數字 5  * 遍曆第一次結果: 6  * _____________ 7  * 4, 6, 2, 3, 5 8  * 4, 2, 6, 3, 5 9  * 4, 2, 3, 6, 510  * 4, 2, 3, 5, 611  */12 public class BubbleSortDemo {13     public static void main(String[] args) {14         int[] arr = {4, 6, 2, 3, 5};15         bubbleSort(arr);16         for (int i = 0; i < arr.length; i++) {17             System.out.println(arr[i]); // 2, 3, 4, 5, 618         }19     }20     /**21      * 冒泡排序22      */23     public static void bubbleSort(int[] arr) {24         int len = arr.length;25         int temp = 0;26         /*27         外層迴圈:控制排好第幾個數28         內層迴圈:控制相鄰兩個數比較次數29         二者關係(i < len - 1與j < len - 1 - i):隨著外層迴圈多排好1個數,內層迴圈就少迴圈比較一次30         */31         for (int i = 0; i < len - 1; i++) {32             for (int j = 0; j < len - 1 - i; j++) {33                 if (arr[j] > arr[j+1]) {34                     temp = arr[j];35                     arr[j] = arr[j+1];36                     arr[j+1] = temp;37                 }38             }39         }40     }41 42 }

 

最後:推薦一個超級實用的視覺化檢視,目的是可以互動看到程式每一步的狀態及參數是什麼,簡直perfect!

視覺化檢視地址:http://www.pythontutor.com/java.html#mode=edit

介面如下:

 

Java冒泡排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.