Written by Sai Sandeep Thota on April 3, 2013 in C++ > Programming

C++ Program to Implement Bubble Sort using Templates

GET ALERTS:

Get our Latest updates delivered to your mailbox!

We have already implemented Bubble sort without using Function Templates. Template is a powerful feature of Object oriented programming. They give the flexibility to a programmer for using any data type in a function without rewriting the whole boring function for each data type again and again.

Here in this program we have written a function for Bubble sort and we have added a template tag before the function so that, the parameter will be of the data type Name. Everything is same except some variable data types. Take a look at the below program, you’ll get a clear idea.

In the main function we are passing some predefined values into the bubble function by calling the function bubble(a,6) where a is the array containing integers and 6 is the size of array. After passing the values into the function we are displaying the sorted order. You can also rewrite the main function in a way that the user will enter the data and size of the array.

#include<conio.h>
#include<iostream.h>

template<class bubble>
void bubble(bubble a[], int n)
{
	int i, j;
	for(i=0;i<n-1;i++)
	{
		for(j=i+1;j<n;j++)
		{
			if(a[i]>a[j])
			{
				bubble element;
				element = a[i];
				a[i] = a[j];
				a[j] = element;
			}
		}
	}
}

void main()
{
	int a[6]={1,2,3,4,4,3};
	char b[4]={'s','b','d','e'};
	clrscr();
	bubble(a,6);
	cout<<"\nSorted Order Integers: ";
	for(int i=0;i<6;i++)
		cout<<a[i]<<"\t";
	bubble(b,4);

	cout<<"\nSorted Order Characters: ";
	for(int j=0;j<4;j++)
		cout<<b[j]<<"\t";
	getch();
}

Output:
bubble-sort-templates

{ 1 comment… read it below or add one }

bubble 60 January 10, 2017 at 9:45 am

There is definately a lot to find out about this issue. I love all
the points you have made.

Reply

Leave a Comment

Previous post:

Next post: