Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and work.

aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Linux Training
Teach Your Child To Read

BlueHost Web Hosting Black Friday

Bonsai Boy of New York Bonsai Trees and Accessories

DreamCloud The Comfortable Luxury Mattress Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


Disclosure We are a professional Programming & Software Q&A website, that receives compensation from some of the links whose we show you with Information. It means that my content may contain affiliate links.

16,919 questions

22,608 answers

573 users

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
...