冒泡排序算法原理及JAVA實現(xiàn)代碼
冒泡排序法:關鍵字較小的記錄好比氣泡逐趟上浮,關鍵字較大的記錄好比石塊下沉,每趟有一塊最大的石塊沉底。
算法本質:(最大值是關鍵點,肯定放到最后了,如此循環(huán))每次都從第一位向后滾動比較,使最大值沉底,最小值上升一次,最后一位向前推進(即最后一位剛確定的最大值不再參加比較,比較次數(shù)減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;
}
}
}
}
}
相關文章
SpringBoot如何優(yōu)雅的整合Swagger Api自動生成文檔
在多人協(xié)作的開發(fā)過程中,API文檔不僅可以減少等待,也能保證開發(fā)的持續(xù)進行,這篇文章主要給大家介紹了關于SpringBoot如何優(yōu)雅的整合Swagger Api自動生成文檔的相關資料,需要的朋友可以參考下2021-07-07SpringBoot項目讀取外置logback配置文件的問題及解決
SpringBoot項目讀取外置logback配置文件的問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08