Answer to Question #204738 in C++ for Root

Question #204738

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.


1
Expert's answer
2021-06-08T23:49:40-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog