(S.E SPPU) Implement C++/Java/Python program for Selection sort using function template | Globaleducore.com
C++ program for Class Templates.
 |
Selection Sort Using Function Template |
Problem Statement:
Implement C++/Java/Python program for Selection sort using function template.
Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.
Problem Solution:
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class T>
void sort(T a[],int n)
{
int i,j,min;
T temp;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
{
min=j;
}
}
if(min!=i)
{ temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
}
template<class T>
void get(T a[],int n)
{
for(int i=0;i<n;i++)
{
cin>>a[i];
}
}
template<class T>
void display(T a[],int n)
{
for(int j=0;j<n;j++)
{
cout<<a[j]<<"\n";
}
}
int main()
{
int a[5],ch,ch1,n;
float b[5];
char c[5],op;
while(1)
{
cout<<"1.int 2.float 3.char 4.exit";
cin>>ch;
switch(ch)
{
case 1:
cout<<"enter no of elements";
cin>>n;
do
{
cout<<"1.get 2.display 3.sort";
cin>>ch1;
switch(ch1)
{
case 1:get(a,n);break; case 2:display(a,n);break;
case 3:sort(a,n);break;
}
cout<<"do you want to continue:";
cin>>op;
}
while(op=='Y'||op=='y');
break;
case 2:
cout<<"enter no of elements";
cin>>n;
do
{
cout<<"1.get 2.display 3.sort";
cin>>ch1;
switch(ch1)
{
case 1:get(b,n);break; case 2:display(b,n);break;
case 3:sort(b,n);break;
}
cout<<"do you want to continue:";
cin>>op;
}
while(op=='Y'||op=='y');
break;
case 3:
cout<<"enter no of elements";
cin>>n;
do
{
cout<<"1.get 2.display 3.sort";
cin>>ch1;
switch(ch1)
{
case 1:get(c,n);break; case 2:display(c,n);break;
case 3:sort(c,n);break;
}
cout<<"do you want to continue:";
cin>>op;
}
while(op=='Y'||op=='y');
break;
case 4: exit(0);
}
}
}
Javascript DisablePlease Enable Javascript To See All Widget
Post a Comment