国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

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

2019-11-26 15:45:35
字體:
來源:轉載
供稿:網友

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

算法本質:(最大值是關鍵點,肯定放到最后了,如此循環)每次都從第一位向后滾動比較,使最大值沉底,最小值上升一次,最后一位向前推進(即最后一位剛確定的最大值不再參加比較,比較次數減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;
    }
   }
  }
 }
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 蒙山县| 盈江县| 宜章县| 玉环县| 翼城县| 双桥区| 本溪| 达尔| 宜兰县| 广昌县| 峨眉山市| 昌都县| 宁城县| 桑日县| 横山县| 渑池县| 亳州市| 治县。| 随州市| 辉县市| 崇明县| 沽源县| 县级市| 高要市| 呼和浩特市| 平度市| 玉龙| 新郑市| 灵台县| 乌鲁木齐县| 洱源县| 同德县| 任丘市| 如东县| 准格尔旗| 河北区| 南通市| 宜城市| 塘沽区| 泰安市| 福贡县|