冒泡排序函数模板c++
时间: 2023-12-23 13:27:51 浏览: 101
以下是一个使用模板的冒泡排序函数的C++示例:
```cpp
#include <iostream>
using namespace std;
template <typename T>
void bubbleSort(T arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
}
}
}
}
int main() {
int intArr[] = {64, 34, 25, 12, 22, 11, 90};
int intArrSize = sizeof(intArr) / sizeof(int);
bubbleSort(intArr, intArrSize);
cout << "Sorted int array: ";
for (int i = 0; i < intArrSize; i++) {
cout << intArr[i] << " ";
}
cout << endl;
double doubleArr[] = {3.14, 2.71, 1.618, 0.618};
int doubleArrSize = sizeof(doubleArr) / sizeof(double);
bubbleSort(doubleArr, doubleArrSize);
cout << "Sorted double array: ";
for (int i = 0; i < doubleArrSize; i++) {
cout << doubleArr[i] << " ";
}
cout << endl;
return 0;
}
```
阅读全文
相关推荐
















