更新時間:2019-11-20 來源:黑馬程序員 瀏覽量:
讓數(shù)組中的兩個相鄰數(shù)字進(jìn)行比較,數(shù)組中較大的值向下沉,值小的上浮,就類似于水中的氣泡,較大的下沉,較小的上升,慢慢冒出來。簡單的說就是數(shù)值大的會慢慢往前排,數(shù)據(jù)值小的會慢慢向后排,最終實現(xiàn)由小到達(dá)排列,最小的排在最前,最大的排到最后。
冒泡排序圖解:
算法執(zhí)行前
算法執(zhí)行后
冒泡算法執(zhí)行過程【動圖版】
冒泡排序算法JAVA實現(xiàn)代碼
import com.jiajia.ArrayUtil.*; // 按包名導(dǎo)入
public class BubbleSortMain {
public static void main(String[] args) {
int[] arr = {3,43,38,5,47,15,36,26,27,2,44,4,50,19,38};
bubbleSort(arr);
ArrayUtil.print(arr);
}
/**
* 冒泡排序
*/
private static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - i -1; j++) { // 這里說明為什么需要-1
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
def bubble_sort(the_list):
i = 0
while i < len(the_list):
j = 0
while j < len(the_list)-1:
print(the_list[j],the_list[j+1])
if the_list[j] > the_list[j+1]:
the_list[j], the_list[j+1] = the_list[j+1], the_list[j]
j = j+1
print(the_list)
print("======"+str(the_list))
i = i+1
return the_list
if __name__ == '__main__':
the_list = [3, 43, 38, 5, 47, 15, 36, 26, 27, 2, 44, 4, 50, 19, 38]
print("排序前:" + str(the_list))
print("排序后:" + str(bubble_sort(the_list)))
原文:冒泡排序算法
【AI設(shè)計】北京143期畢業(yè)僅36天,全員拿下高薪offer!黑馬AI設(shè)計連續(xù)6期100%高薪就業(yè)
2025-09-19【跨境電商運營】深圳跨境電商運營畢業(yè)22個工作日,就業(yè)率91%+,最高薪資達(dá)13500元
2025-09-19【AI運維】鄭州運維1期就業(yè)班,畢業(yè)14個工作日,班級93%同學(xué)已拿到Offer, 一線均薪資 1W+
2025-09-19【AI鴻蒙開發(fā)】上海校區(qū)AI鴻蒙開發(fā)4期5期,距離畢業(yè)21天,就業(yè)率91%,平均薪資14046元
2025-09-19【AI大模型開發(fā)-Python】畢業(yè)33個工作日,就業(yè)率已達(dá)到94.55%,班均薪資20763元
2025-09-19【AI智能應(yīng)用開發(fā)-Java】畢業(yè)5個工作日就業(yè)率98.18%,最高薪資 17.5k*13薪,全班平均薪資9244元
2025-09-19