冒泡排序演算法原理及JAVA實現代碼_java

來源:互聯網
上載者:User

冒泡排序法:關鍵字較小的記錄好比氣泡逐趟上浮,關鍵字較大的記錄好比石塊下沉,每趟有一塊最大的石塊沉底。

演算法本質:(最大值是關鍵點,肯定放到最後了,如此迴圈)每次都從第一位向後滾動比較,使最大值沉底,最小值上升一次,最後一位向前推進(即最後一位剛確定的最大值不再參加比較,比較次數減1)

複雜度: 時間複雜度 O(n2) ,空間複雜度O(1)

JAVA原始碼(成功運行,需要Date類)

複製代碼 代碼如下:

 public static void bubbleSort(Date[] days) {
  int len = days.length;
  Date temp;
  for (int i = len - 1; i >= 1; i--) {
   for (int j = 0; j < i; j++) {
    if (days[j].compare(days[j + 1]) > 0) {
     temp = days[j + 1];
     days[j + 1] = days[j];
     days[j] = temp;
    }
   }
  }
 }
class Date {
 int year, month, day;

 Date(int y, int m, int d) {
  year = y;
  month = m;
  day = d;
 }

 public int compare(Date date) {
  return year > date.year ? 1 : year < date.year ? -1
    : month > date.month ? 1 : month < date.month ? -1
      : day > date.day ? 1 : day < date.day ? -1 : 0;
 }

 public void print() {
  System.out.println(year + " " + month + " " + day);
 }
}

複製代碼 代碼如下:

package testSortAlgorithm;

public class BubbleSort {
 public static void main(String[] args) {
  int array[] = { 5, 6, 8, 4, 2, 4, 9, 0 };
  bubbleSort(array);
  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i]);
  }
 }

 public static void bubbleSort(int array[]) {
  int temp;
  for (int i = array.length - 1; i > 0; i--) {
   for (int j = 0; j < i; j++) {
    if (array[j] > array[j + 1]) {
     temp = array[j];
     array[j] = array[j + 1];
     array[j + 1] = temp;
    }
   }
  }
 }
}

聯繫我們

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