【資料結構與演算法】冒泡排序

來源:互聯網
上載者:User

標籤:冒泡排序   資料結構   排序演算法   

排序演算法是一種基本、常用的演算法。排序演算法分為內部排序和外部排序。

內部排序是指整個排序過程不需要訪問外存就能完成。

外部排序是指黨對大批量資料進行排序時,不可能一次性將全部資料裝入記憶體,只能從外存讀取一部分資料到記憶體中,將記憶體中的資料進行排序後,再儲存到外存中,然後再從外存中讀取下一部分資料到記憶體中,最後,對已經排序的子部分進行歸併排序。

冒泡排序是一種相鄰資料交換的排序方法。冒泡排序的特點是對於n個元素要進行n-1次掃描,那麼有時候可能掃描一兩次資料就已經排好序了,後面再掃描明顯就是浪費計算資源了,所以可以對冒泡排序進行一些改進,代碼如下:

public class BubbleSort {public void bubbleSort(int[] in) {boolean isBubble = false;int inLength = in.length;for (int i = 0; i < inLength; i++) {System.out.print("第" + i + "遍: ");for (int k : in) {System.out.print(k + " ");}System.out.println();for (int j = inLength - 1; j > i; j--) {if (in[j] < in[j - 1]) {isBubble = true;int tmp = in[j];in[j] = in[j - 1];in[j - 1] = tmp;}}if (!isBubble) {break;} else {isBubble = false;}}}public static void main(String[] args) {BubbleSort mBubbleSort = new BubbleSort();int[] caseOne = { 6, 5, 4, 3, 2, 1, 10, 2 };int[] caseTwo = { 1, 6, 5, 2, 4, 3 };mBubbleSort.bubbleSort(caseOne);for (int i : caseOne) {System.out.print(i + " ");}System.out.println();mBubbleSort.bubbleSort(caseTwo);for (int i : caseTwo) {System.out.print(i + " ");}}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.