氣泡排序重複遍歷陣列,比較相鄰元素並交換順序錯誤的配對,大元素像氣泡浮到陣列末端。時間複雜度 O(n²),穩定排序,可透過旗標優化最好情況至 O(n)。
using System;
public class BubbleSorter
{
public void Sort(int[] list)
{
bool swapped;
for (int pass = 1; pass < list.Length; pass++)
{
swapped = false;
for (int i = 0; i < list.Length - pass; i++)
{
if (list[i] > list[i + 1])
{
int temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
swapped = true;
}
}
if (!swapped) break; // 提前結束
}
}
}
// 測試
public class Program
{
public static void Main()
{
int[] arr = { 1, 5, 13, 6, 10, 55, 99, 2, 87, 12, 34, 75, 33, 47 };
new BubbleSorter().Sort(arr);
Console.WriteLine(string.Join(" ", arr));
}
}
Array.Sort/List.Sort 採用 Introsort (快速+堆積+插入混合),效能遠超過氣泡排序。