#include <iostream>
using namespace std;
/**
* 冒泡排序
* @tparam T 数组类型
* @param arr 数组名
* @param n 长度
*/
template<class T>
void bubbleSort(T arr[], int n) {
for (int i = 0; i < n - 1; ++i) {
int flag = 0;
for (int j = 0; j < n - 1 - i; ++j) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
flag = 1;
}
}
if (!flag) {
break;
}
}
}
int main() {
int arr[] = {-1, 0, -2, 1, 9, 0, 2, 5, 4, 3};
int len = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, len);
for (const int &temp: arr) {
cout << temp << " ";
}
cout << endl;
return 0;
}
冒泡排序-C++
最新推荐文章于 2022-01-20 12:09:51 发布