注:本文以升序為例
一、冒泡排序
1.1 操作方法
步驟1 | 比較相鄰元素,如果前者比后者大,則交換它們。 |
步驟2 | 對頭到尾,對所有元素按序執行一輪這樣的操作(這樣可以找到第一最大值) |
步驟3 | 再從第一個元素開始,重復上述比較操作,但比較次數比上一輪少一次,直至結束 |
1.2 示例代碼
#include <iostream>using namespace std;void bubble_sort(int *a, int len) {for(int i = 0; i < len-1; i++) {for(int j = 0; j < len-i-1; j++) {if(a[j] > a[j+1]) {//交換int tmp = a[j];a[j] = a[j+1];a[j+1] = tmp; }}}
} //輸出數組內容
void print(int *a, int len) {for(int i = 0; i < len; i++) {cout << a[i] << ' ';}cout << endl;
} int main() {int a[10] = {2, 4, 5, 9, 7, 0, 8, 6, 3, 1};cout << "Before sort : " << endl; print(a, 10);bubble_sort(a, 10);cout << "After sort : " << endl;print(a, 10);return 0;
}
輸出結果示意圖: