气泡排序
1,氣泡排序的思想
對(duì)比相鄰兩個(gè)元素的相對(duì)大小,如果當(dāng)前第i個(gè)元素小于前一個(gè)元素則交換兩元素的值,每遍歷一輪數(shù)組元素的個(gè)數(shù)減一,直到所有交換操作完成,不在發(fā)生交換。
2,代碼實(shí)現(xiàn)
#include <iostream>
#include <algorithm>using namespace std;template<typename T>
void bubbleSort(T arr[], int n) {bool swapped;do {swapped = false;for (int i = 1; i < n; i++)if (arr[i - 1] > arr[i]) {swap(arr[i - 1], arr[i]);swapped = true;}n--;} while (swapped);
}int main() {int a[10] = { 10,9,8,7,6,5,4,3,2,1 };bubbleSort(a, 10);for (int i = 0; i < 10; i++)cout << a[i] << " ";cout << endl;return 0;
}
總結(jié)
- 上一篇: 批标准归一化(Batch Normali
- 下一篇: HDU1089-1096 A+B for