Write a C++ generic bubblesort function using templates that takes as parameters an array and its size. You may assume that the compared objects have a < operator already defined. Test your template function with a built-in type and a user-defined type.
#include <iostream>
template<typename T>
void bubbleSort(T *arr, int n)
{
for (int i = n-1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
if (arr[j+1] < arr[j]) {
T t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}
}
int main()
{
int a[4] {4, 5, 2, 5};
bubbleSort(a, 4);
for (int i = 0; i < 4; i++) {
std::cout << a[i] << " ";
}
return 0;
}
Comments
Leave a comment