排序演算法——冒泡排序

來源:互聯網
上載者:User

標籤:print   cep   algorithm   argument   測試   ack   empty   第一個   ase   

package com.java.base.sort.algorithm;/** * 冒泡排序 * * <p>演算法思路: * * <p>1.從數列第一個數開始,比較每相鄰的兩個數, 將較大(或較小)數交換至後面,直到將最大的數交換到數列最後 * * <p>2.再迴圈第一步直到數列中只剩下第一個數 * * 演算法複雜度:O(n2) * 穩定性:穩定 * * @author lxy */public class BubbleSort {  /**   * 交換   */  private static void swap(int[] array, int m, int n) {    int tmp = array[m];    array[m] = array[n];    array[n] = tmp;  }  /**   * 冒泡排序:9,8,11,17,12,2,4,5,20,3,1   */  public static int[] bubbleSort(int[] array) {    if (array == null || array.length == 0) {      throw new IllegalArgumentException("array must be not empty!");    }    if (array.length == 1) {      return array;    }    for (int i = array.length - 1; i > 0; i--) {      for (int j = 0; j < i; j++) {        if (array[j] > array[j + 1]) {          swap(array, j, j + 1);        }      }    }    return array;  }  /**   * 測試   */  public static void main(String[] args) {    int[] array = {9, 8, 11, 17, 12, 2, 4, 5, 20, 3, 1};    System.out.println("冒泡排序前:");    for (int i = 0; i < array.length; i++) {      System.out.print(array[i]);      System.out.print(",");    }    array = BubbleSort.bubbleSort(array);    System.out.println("\n冒泡排序後:");    for (int i = 0; i < array.length; i++) {      System.out.print(array[i]);      System.out.print(",");    }  }}

執行結果:

冒泡排序前:9,8,11,17,12,2,4,5,20,3,1,冒泡排序後:1,2,3,4,5,8,9,11,12,17,20,

排序演算法——冒泡排序

聯繫我們

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