冒泡排序算法原理及JAVA實(shí)現(xiàn)代碼
冒泡排序法:關(guān)鍵字較小的記錄好比氣泡逐趟上浮,關(guān)鍵字較大的記錄好比石塊下沉,每趟有一塊最大的石塊沉底。
算法本質(zhì):(最大值是關(guān)鍵點(diǎn),肯定放到最后了,如此循環(huán))每次都從第一位向后滾動(dòng)比較,使最大值沉底,最小值上升一次,最后一位向前推進(jìn)(即最后一位剛確定的最大值不再參加比較,比較次數(shù)減1)
復(fù)雜度: 時(shí)間復(fù)雜度 O(n2) ,空間復(fù)雜度O(1)
JAVA源代碼(成功運(yùn)行,需要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;
}
}
}
}
}
相關(guān)文章
Spring Boot + Mybatis-Plus實(shí)現(xiàn)多數(shù)據(jù)源的方法
這篇文章主要介紹了Spring Boot + Mybatis-Plus實(shí)現(xiàn)多數(shù)據(jù)源的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
Java并發(fā)編程中的CyclicBarrier使用解析
這篇文章主要介紹了Java并發(fā)編程中的CyclicBarrier使用解析,CyclicBarrier從字面意思上來看,循環(huán)柵欄,這篇文章就來分析下是到底是如何實(shí)現(xiàn)循環(huán)和柵欄的,需要的朋友可以參考下2023-12-12
NameNode?重啟恢復(fù)數(shù)據(jù)的流程詳解
這篇文章主要為大家介紹了NameNode?重啟恢復(fù)數(shù)據(jù)的流程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
MyBatis開發(fā)Dao層的兩種方式實(shí)現(xiàn)(原始Dao層開發(fā))
這篇文章主要介紹了MyBatis開發(fā)Dao層的兩種方式實(shí)現(xiàn)(原始Dao層開發(fā)),并對數(shù)據(jù)庫進(jìn)行增刪查改,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12

