0% found this document useful (0 votes)
74 views

Sorting Using Templates

This document contains C++ code to implement bubble sort and quick sort algorithms. It includes functions to sort both integer and character arrays using bubble sort. It also includes functions to implement quick sort using templates and a swap function. The main function prompts the user for the number of elements and values, calls the quick sort function, and displays the sorted output.

Uploaded by

kalpanasripathi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Sorting Using Templates

This document contains C++ code to implement bubble sort and quick sort algorithms. It includes functions to sort both integer and character arrays using bubble sort. It also includes functions to implement quick sort using templates and a swap function. The main function prompts the user for the number of elements and values, calls the quick sort function, and displays the sorted output.

Uploaded by

kalpanasripathi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

PROGRAMMING

&
DATA STRUCTURES II
ASSIGNMENT III

SUBMITTED BY
C. GEETHA VARSHA
II CSE A

BUBBLE SORT
#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:
Sorted Order Integers : 1

Sorted Order Characters : b

QUICK SORT
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
template<class t>
void quick(t a[],int low,int high)
{
t key;
int i,j,flag=1;
if(low<high)
{
key=a[low];
i=low+1;
j=high;
while(flag)
{
while((a[i]<=key) && (i<j))
i++;

while(a[j]>key)
j--;
if(i<j)
swap(a,i,j);
else
flag=0;
}
swap(a,low,j);
quick(a,low,j-1);
quick(a,j+1,high);
}
}

template<class t1>
void swap(t1 a[],int x,int y)
{
t1 temp;
temp=a[x];
a[x]=a[y];
a[y]=temp;
}
void main()
{
int i,n,a[20];
clrscr();
cout<<"Enter the number of elements to be sort::";
cin>>n;
cout<<"Enter elements:\n";
for(i=0;i<n;i++)
cin>>a[i];
quick(a,0,n-1);

cout<<"The sorted elements are:\n";


for(i=0;i<n;i++)
cout<< a[i]<<endl;;
getch();
}

OUTPUT:
Enter the number of elements to be sorted: 5
Enter elements:
5
2
4
1
3
The sorted elements are:
1
2
3
4
5

You might also like