Skip to main content

Insertion sort, bubble sort or Selection sort Using templates


    Use generic class to sort a list of elements. Give user the option to perform sorting using Insertion sort, bubble sort or Selection sort. Use templates.

#include<iostream>
#include<limits>

using namespace std;

template <class T>
class sorting
{
T a[10];
public:
void get_item()
{
for(int i=0;i<10;i++)
{
cout<<"\n a["<<i<<"] = ";
cin>>a[i];
}
}


void sel_sort()
{
T temp;

for(int i=0;i<10;i++)
{
for(int j=i+1;j<10;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}

void bub_sort()
{
T temp;

for(int i=0;i<10;i++)
{
for(int j=0;j<10-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}

void inst_sort()
{
T tmp;
int j;

for(int i=1;i<10;i++)
{
tmp=a[i];
j=i-1;
while(tmp<a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1]=tmp;
}
}


void display()
{
for(int i=0;i<10;i++)
{
cout<<" "<<a[i]<<", ";
}
cout<<"\n\n";
}

};// End of Class


void main()
{
// Creating Integer Array using Template
sorting<int> iarr;

cout<<"\n\n Enter Elements of Integer Array\n";
iarr.get_item();
cout<<"\n\n Elements of Integer Array\n";
iarr.display();
iarr.sel_sort();
cout<<"\n\n After Selection Sorting\n Elememts of Integer Array\n";
iarr.display();
iarr.bub_sort();
cout<<"\n\n After Bubble Sorting\n Elememts of Integer Array\n";
iarr.display();
iarr.inst_sort();
cout<<"\n\n After Insertion Sorting\n Elememts of Integer Array\n";
iarr.display();

// Creating Double Array using Template
sorting<double> darr;
cout<<"\n\n Enter Elements of Double Array\n";
darr.get_item();
cout<<"\n\n Elements of Double Array\n";
darr.display();
darr.sel_sort();
cout<<"\n\n After Selection Sorting\n Elememts of Double Array\n";
darr.display();
darr.bub_sort();
cout<<"\n\n After Bubble Sorting\n Elememts of Double Array\n";
darr.display();
darr.inst_sort();
cout<<"\n\n After Insertion Sorting\n Elememts of Double Array\n";
darr.display();

system("pause");
}


Output:-










Comments

Post a Comment

Popular posts from this blog

Use Case Diagram for Online Book Store

Online Movie Ticket Booking Sequence Diagram

Linear search & Binary search using Template

Write a program to search an element from a list. Give user the option to perform Linear or Binary search. Use Template functions. #include<iostream> using namespace std; template <class T> void Lsearch(T *a, T item, int n) { int z=0; for(int i=0;i<n;i++) { if(a[i]== item) { z=1; cout<<"\n Item found at position = "<<i+1<<"\n\n"; } else if(z!=1) { z=0; } } if(z==0) cout<<"\n Item not found in the list\n\n"; } template <class T> void Bsearch(T *a, T item, int n) { int beg=0,end=n-1; int mid=beg+end/2; while((a[mid]!=item) && (n>0)) { if(item>a[mid]) beg=mid; else end=mid; mid=(beg+end)/2; n--; } if(a[mid]==item) cout<<"\n Item found at position = "<<mid+1<<"\n\n"; else cout<<"\n Item not found in the list\n\n"; } void main() { int iarr[10] = {2,42,56,86,87,99,323,546,767,886};