How to write generic bubble sort algorithm to sort arrays of numbers in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

template <class BBL> void bubbleSort(BBL *arr, int size)
{
	BBL tmp;

	for (int i = 1; i < size; i++)
		for (int j = size - 1; j >= i; j--)
			if (arr[j - 1] > arr[j]) {
				tmp = arr[j - 1];
				arr[j - 1] = arr[j];
				arr[j] = tmp;
			}
}
template <class BBL> void print(BBL *arr, int size)
{
	for (int i = 0; i < size; i++)
		cout << arr[i] << ' ';
	cout << endl;
}

int main()
{
	int arrint[] = { 7, 3, 9, 2, 1, 8, 1, 5, 4 };

	bubbleSort(arrint, 9);
	print(arrint, 9);

	double arrdouble[] = { 3.14, 1.11, 1.21, 5.67, 3.98 };

	bubbleSort(arrdouble, 5);
	print(arrdouble, 5);

	return 0;
}


/*
run:

1 1 2 3 4 5 7 8 9
1.11 1.21 3.14 3.98 5.67

*/

 



answered Aug 1, 2018 by avibootz

Related questions

3 answers 392 views
1 answer 267 views
1 answer 287 views
3 answers 616 views
1 answer 217 views
1 answer 168 views
1 answer 182 views
...