1. 演算法
n筆資料由左而右依序兩筆資料相互比較,若前者大於後者則前後交換,共做n-1回合。若某一回合中完全無swap發生,則代表sort完成。
void Sort(char *arr){
int n = strlen(arr);
for (int i = 0; i < n; i++){
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1]){ //swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
演算法分析:
input={5,3,8,2,6}
i=0, j=0 to 3j=0⇒3,5,8,2,6j=1⇒×j=2⇒3,5,2,8,6j=3⇒3,5,2,6,8
i=1, j=0 to 2j=0⇒×j=1⇒3,2,5,6,8j=2⇒×
i=2, j=0 to 1j=0⇒2,3,5,6,8j=1⇒×
2. 性質
Time Complexity:
Best Case: 資料恰好由小到大排列 O(n)
Worst Case: 資料恰好由大到小排列 O(n2)
比較次數= (n−1)+(n−2)+...+1=2n(n−1)
Avg Case: O(n2)
Bubble sorting is a stable sorting method.