依然是一種最簡單基本、容易理解的排序演算法。
基本概念:由左而右,依序兩兩前後記錄相比較,若前者>後者,則swap(前,後),每一回合後,當時之最大值會升至最高位置。
若某回合完全沒有進行swap,則表示sort完成。
Time complexity:
Stable。
ex: Input:...,5,...,5*,...
因5 !> 5* 所以不會swap。
BubbleSort(list,n)
{ for i=1 to (n-1) do
{ f=0; //f表有無發生swap,0:無,1:有
for j=1 to (n-i) do
{
if list[j]>list[j+1] then
{ swap(list[j],list[j+1])
f=1;
}
if(f==0) then exit;
}
}
}