冒泡排序是排序算法中最基礎、最容易理解的入門級算法之一。因其邏輯簡單直觀,常被用作計算機科學課程中排序算法的首個教學案例。名稱來源於排序過程中,較大的元素如同水泡般從序列底部逐步「冒升」到頂部的特性。
冒泡排序通過重複遍歷待排序序列,比較相鄰元素並在順序錯誤時交換位置。每一輪遍歷都會將當前未排序部分的最大元素移動到正確位置。以序列 {10, 2, 11, 8, 7} 為例:

package com.algorithm.sort.bubble;
import java.util.Arrays;
public class Bubble {
public static void main(String[] args) {
int[] nums = {10, 2, 11, 8, 7};
nums = bubbleSort(nums);
System.out.println(Arrays.toString(nums));
}
private static int[] bubbleSort(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length - i - 1; j++) {
if (nums[j] > nums[j + 1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
return nums;
}
}
def bubble_sort(nums):
for i in range(len(nums)):
for j in range(len(nums) - i - 1):
if nums[j] > nums[j + 1]:
temp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = temp
return nums
nums = [10, 2, 11, 8, 7]
nums = bubble_sort(nums)
print(nums)