# Bubble Sort – using Function Template (C++)

April 24, 2016

Categorised in: ,

```<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>/*
Implement C++/Java/Python program for bubble sort using function template
*/

#include<iostream>
using namespace std;
template <typename X>
void show(int n,X arr[]);
template <typename T>
void bubblesort(int n,T arr[])
{
T temp;
cout<<"\n Before sorting elements are:";
show(n,arr);
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;

}
}

}
cout<<"after sorting: \n";
show(n,arr);
}
template <class X>
void show(int n,X arr[])
{
cout<<endl;
for(int k=0;k<n;k++)
{
cout<<arr[k]<<"\t";
}
}
int main()
{
int iarr[100],ch,n;
float farr[100];
do
{
cout<<"\n \t     BUBBLE SORT";
cout<<"\n ———————————";
cout<<"\n  1.Integer elements\n  2.Float element\n  3.Exit";
cout<<"\n ———————————";
cin>>ch;
if(ch==1)
{

cout<<"\n Enter how many Integer Elements :";
cin>>n;
cout<<"\n Enter array elements :";
for(int j=0;j<n;j++)
cin>>iarr[j];
bubblesort(n,iarr);
}
if(ch==2)
{
cout<<"\n Enter how many Float elements :";
cin>>n;
cout<<"\n Enter array element :";
for(int k=0;k<n;k++)
cin>>farr[k];
bubblesort(n,farr);
}

}while(ch!=3);

return 0;
}```