Vous êtes sur la page 1sur 51

1.

1 Write a C++ program that takes all the lines input to standard
Input and writes them to standard output in reverse order.
That is, each line is output in the correct order, but the ordering
of the lines is reversed.

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int main(){
int i=0;
char**Line;
cout<<"enter some lines (* to stop):\n";
Line=new char*[20];
while(true){
Line[i]=new char[30];
gets(Line[i]);//input the line
strrev(Line[i]);//reverse the line
if(!strcmp(Line[i],"*")){//compare for the end statement
delete[] Line[i];//deleted the statement as it is not
included amongst lines
break;
}
i++;
}
cout<<"reversed lines in same order are";
for(int k=0;k<i;k++){
cout<<"\n"<<Line[k];
delete[] Line[k];//deleting the memory allotted after the
lines
have been displayed
}
delete[] Line;
}

1
1.2 The greatest common divisor, or GCD, of two positive
integers n and m is the largest number j, such that n and m
are both multiples of j. Euclid proposed a simple algorithm
for computing GCD(n,m), where n > m, which is based on a
concept known as the Chinese Remainder Theorem. The
main idea of the algorithm is to repeatedly perform modulo
computations of consecutive pairs of the sequence that
starts (n,m, . . .), until reaching zero. The last nonzero
number in this sequence is the GCD of n and write a program
to find GCD of two numbers using this algorithm.

#include<iostream>
using namespace std;
void GCD(int n,int m){
if(m>n){
m=m+n;
n=m-n;
m=m-n;
}
if(m==0){
cout<<"GCD of (n,m) is: "<<n;
//as in Chinese Remainder Theorem n is GCD if m
//is zero in pair (n,m)
return;
}
GCD(m,n%m);//recursive call as by the theorem
}
int main(){
int m,n;
cout<<"enter n, m (n>m)numbers to calculate their GCD: ";
cin>>n>>m;
GCD(n,m);
return 0;
}

2
1.3 Write a C++ program that outputs all possible strings formed by
using each of the characters 'a', 'b', 'c', 'd', 'e', and 'f' exactly once.

#include<iostream>
using namespace std;
int c=1;
void swap(char&x,char&y){
char temp=x;
x=y;
y=temp;
}
void perm(char*a,int l,int r){
//function takes parameters as:
//(string,index of first element,index of last element)
int i;
if(l==r){
cout<<c<<". "<<a<<"\n";//output the string
c++;
}
else{
for(i=l;i<=r;i++){
swap(a[l],a[i]);
perm(a,l+1,r);//recursive call find all possible strings
swap(a[l],a[i]);
}
}
}
int main(){
char str[]="abcdef";
perm(str,0,5);
return 0;
}

3
1.4 Write a program to store the student's record in a file. The format
of a record is as follows :(Sno.,Students Name, Fathers Name,
DOB(dd/mm/yyyy),Current Address, Mobile No., Email
Address)Write a function findAge() which returns the age of a
student based on the student's serial number. To do this, the
function reads the students records from file and calculates the
age of a student based on his/her DOB.

#include<iostream>
#include<cstdio>
#include<ctime>
#include<fstream>
using namespace std;
struct DOB{ //for storing DOB in format of dd mm yy
int dd,mm,yy;
};
struct Student{//main structure, which defines the required data types
int serial_no;
char student_name[30],father_name[30];
DOB dob;//object of structure DOB as to store DOB in dd mm yy format
char current_address[50],email_address[20];
long mobile_no;
}*s;
int findAge(int sno){//function takes serial number as argument and
calculates the age of student by searching the DOB
time_t curTime=time(0);
tm *tmData=localtime(&curTime);
int year=tmData->tm_year+1900;
int month=tmData->tm_mon+1;
int day=tmData->tm_mday;
int i=0;
ifstream f;
f.open("Student_record.txt",ios::in);//to open the file in write mode
Student s;
while(!f.eof()){//read the file till it reached the end
f.read((char*)&s,sizeof(s));
if(s.serial_no==sno){
year=year-s.dob.yy;
if(month<=s.dob.mm){//logic considering month and day
if(month==s.dob.mm){
//reduces the year by 1 if month of entry is less than
4
if(day<s.dob.dd) year--;//month in DOB
}
else year--;
}
i++;
break;
}
}
f.close();
if(i==1)
return year;
cout<<"no such data found!";
}
int main(){
char ch='y';
ofstream f;//to open the file in read mode
f.open("Student_record.txt",ios::out|ios::app);
while(ch=='y'||ch=='Y'){
s=new Student;
cout<<"enter serial no.: ";cin>>s->serial_no;cin.get();
cout<<"enter student's name: ";gets(s->student_name);
cout<<"enter father's name: ";gets(s->father_name);
cout<<"enter DOB(dd mm yy): ";cin>>s->dob.dd>>s->dob.mm>>s-
>dob.yy;cin.get();
cout<<"enter current address: ";gets(s->current_address);
cout<<"enter email address: ";gets(s->email_address);
cout<<"enter moblie no.: ";cin>>s->mobile_no;
f.write((char*)s,sizeof(Student));
delete s;
cin.get();
cout<<"want to enter more data (Y/N)?";cin.get(ch);;
}
f.close();
int sno=0;
cout<<"enter the Sno. of student to calculate age: ";cin>>sno;
cout<<"the age of the student with Sno."<<sno<<" is: "<<findAge(sno);
}

5
1.5 Write a program which finds the product of two matrices using
dynamic memory allocation. You have to read the inputs from a file
"Input.txt which consists of
3 3 //no. of rows and columns of first matrix
2 2//no. of rows and columns of second matrix
246
135
5 7 9 //first matrix data
78
2 5 //second matrix data

#include<iostream>
#include<fstream>
using namespace std;
int main(){
int i,j,k;
int **M1,**M2,**Result;//declaration of matrices
M1= new int*[3]; M2= new int*[3];
Result= new int*[3];
ifstream f;
f.open("MatrixRead.txt");//to read the data from specified file
for(i=0;i<3;i++){ M1[i]=new int[3];
for(j=0;j<3;j++) f>>M1[i][j];
}
for(i=0;i<3;i++){ M2[i]=new int[3];
for(j=0;j<3;j++) f>>M2[i][j];
}
for(i=0;i<3;i++){
Result[i]=new int[3];
for(j=0;j<3;j++){ Result[i][j]=0;
for(k=0;k<3;k++) Result[i][j]=Result[i][j]+M1[i][k]*M2[k][j];
}
}
for(i=0;i<3;i++){
for(j=0;j<3;j++) cout<<Result[i][j]<<" ";//output the result matrix
cout<<"\n";
}
return 0;
}
//The file MatrixRead.txt, contains: 1 line, that is:
2 3 4 5 6 7 8 9 1 3 5 1 4 8 1 4 5

6
2.1 Write a program which implements insertion sort algorithm on a
given array of integers. Modify your code so that it allows early
termination in case the array is already sorted.

#include<iostream>
using namespace std;
bool is_sorted(int a[],int n){
//Function to check whether array is sorted or not
if(n==1)return true;
int c=0;
for(int i=1,temp1=a[0];i<n;i++){
if(temp1<a[i])temp1=a[i];
else{
c++;
break;
}
}
if(c==0)
return true;//if array is sorted
return false;//if array isnt sorted
}
void insertion_sort(int arr[],int n){
//function to apply insertion sort algorithm
int i,j,temp;
for(i=1;i<n;i++){
temp=arr[i];
j=i-1;
while(temp<arr[j]&&j>-1){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=temp;
if(is_sorted(arr+i,n-i))
return;
}
}
7
int main(){
int n,i;
int temp1,k;
k=0;
cout<<"enter the number of elements in the array: ";
cin>>n;
int *arr=new int[n];
cout<<"enter array:\n";
cout<<"element 1: ";
cin>>arr[0];
temp1=arr[0];
for(i=1;i<n;i++){
cout<<"element "<<i+1<<": ";
cin>>arr[i];
if(temp1<=arr[i])
temp1=arr[i];
//initial check if the array is already sorted
else
k++;
}
if(k==0){
cout<<"array is already sorted ";
delete[] arr;
return 0;
}
insertion_sort(arr,n);
cout<<"sorted array:";
for(i=0;i<n;i++){
cout<<" "<<arr[i];
}
delete[] arr;
return 0;
}

8
2.2 Write a program which implements selection sort algorithm
on a given array of integers. Modify your code so that it
allows early termination in case the array is already sorted.

#include<iostream>
using namespace std;
bool is_sorted(int a[],int n){
//Function to check whether array is sorted or not
int c=0;
for(int i=1,temp1=a[0];i<n;i++){
if(temp1<a[i])temp1=a[i];
else{
c++;
break;
}
}
if(c==0)
return true;//if array is sorted
return false;//if array isnt sorted
}
int find_max(int a[],int x){
//function to find out the max element from the array
int temp=a[0];
for(int i=1;i<x;i++){
if(a[i]>temp)
temp=a[i];
}
return temp;
}
void selection_sort(int arr[],int n){
//function to apply selection sort algorithm
int i,j,k=1;
for(i=n-1;i>-1;i--){
arr[i]=find_max(arr-i,n-i);
}
}
9
int main(){
int n,i;
int temp1,k;
k=0;
cout<<"enter the number of elements in the array: ";
cin>>n;
int *arr=new int[n];
cout<<"enter array:\n";
cout<<"element 1: ";
cin>>arr[0];
temp1=arr[0];
for(i=1;i<n;i++){
cout<<"element "<<i+1<<": ";
cin>>arr[i];
if(temp1<arr[i])temp1=arr[i];
else k++;
}
if(k==0){
cout<<"array is already sorted ";
delete[] arr;
return 0;
}
selection_sort(arr,n);
cout<<"sorted array:";
for(i=0;i<n;i++){
cout<<" "<<arr[i];
}
delete[] arr;
return 0;
}

10
2.3 Write a program which implements bubble sort algorithm on
a given array of integers. Modify your code so that it allows
early termination in case the array is already sorted.

#include<iostream>
using namespace std;
bool is_sorted(int a[],int n){
//function to test whether array is sorted or not
int c=0;
for(int i=1,temp1=a[0];i<n;i++){
if(temp1<a[i])
temp1=a[i];
else{
c++;
break;
}
}
if(c==0)
return true;//is sorted
return false;//if not sorted
}
void bubble_sort(int arr[],int n){
//function to apply bubble sort algorithm
int i,j,k=1;
for(i=0;i<n;i++){
for(j=0;j<n-1;j++){
if(arr[j]>arr[j+1]){
arr[j]=arr[j]+arr[j+1];
arr[j+1]=arr[j]-arr[j+1];
arr[j]=arr[j]-arr[j+1];
}
if(is_sorted(arr,n)) return;
}
}
}
int main(){
int n,i;
int temp1,k=0;
11
cout<<"enter the number of elements in the array: ";
cin>>n;
int *arr=new int[n];
cout<<"enter array:\n";
cout<<"element 1: ";
cin>>arr[0];
temp1=arr[0];
for(i=1;i<n;i++){
cout<<"element "<<i+1<<": ";
cin>>arr[i];
if(temp1<arr[i])
temp1=arr[i];
else k++;
}
if(k==0){
cout<<"array is already sorted ";
delete[] arr;
return 0;
}
bubble_sort(arr,n);
cout<<"sorted array:";
for(i=0;i<n;i++){
cout<<" "<<arr[i];
}
delete[] arr;
return 0;
}

12
2.4 Write a function add() which allows inserting an element in a
sorted array. Also, implement a remove() function which
deletes an element from a sorted array. Test your code with an
example.

#include<iostream>
using namespace std;
void add(int arr[],int& n,int x){
//function to add an element x to an n sized array
int i=n-1;
while(arr[i]>=x&&i>-1){
arr[i+1]=arr[i];
i--;
}
arr[++i]=x;
cout<<"array after adding "<<x<<" is:";
for(i=0;i<n+1;i++)
cout<<" "<<arr[i];
delete[] arr;
}
void remove(int arr[],int n,int x){
//function to remove an element x to an n sized array
int i,j,k=0;
for(i=0;i<n;i++){
if(arr[i]==x)
k++;//test for similar elements
}
if(k==0){
cout<<"element "<<x<<" is not present in the array.";
return;
}
int temp=k;
while(k>0){
for(i=0;i<n;i++){
if(arr[i]==x)
break;
}
13
for(j=i;j<n;j++)
arr[j]=arr[j+1];
k--;
}
n-=temp;
cout<<"array after removing "<<x<<" is:";
for(i=0;i<n+1;i++)
cout<<" "<<arr[i];
delete[] arr;
}
int main(){
int n,i,x;
cout<<"enter the number of elements in the array: ";
cin>>n;
int *arr=new int[n+1];
cout<<"enter a sorted array array:\n";
for(i=0;i<n;i++){
cout<<"element "<<i+1<<": ";
cin>>arr[i];
}
int temp;
cout<<"press (0/1) for (adding/removing) an element to/in
the array: ";
cin>>temp;
switch (temp){
case 0:cout<<"enter the element to be added: ";
cin>>x;
add(arr,n,x); break;
case 1:cout<<"enter the element to be removed: ";
cin>>x;
remove(arr,n-1,x);
break;
default:
cout<<"wrong choice!!!";
delete[] arr;
return 0;
}

14
2.5 Write a program which generates a magic square of n size.
Use the following method for generating a magic square: "Start
with 1 in the middle of the top row. Then go up and left
assigning numbers in the increasing order to empty squares as
tiling the plane and continues; if a square is occupied, move
down instead and continue."

#include<iostream>
using namespace std;
int main(){
int n,i,j,s=1,column,row=0;
cout<<"Enter N for NxN magic square: ";cin>>n;
column=n/2;
if(n%2!=0){//magic square exists for odd number of rows/columns
int **MagicSquare=new int* [n];
for(i=0;i<n;i++)MagicSquare[i]=new int[n];
for(i=0;i<n;i++) for(j=0;j<n;j++)MagicSquare[i][j]=0;
cout<<"The generated magic square is:\n\n";
for(i=0;i<n*n;i++){
if(MagicSquare[row][column]==0){
MagicSquare[row][column]=s; row--; column--;
if(row==-1)row+=n;
if(column==-1)column+=n;
if(MagicSquare[row][column]!=0){
column++; row++;
if(row==n) row=0;
if(column==n) column=0;}
}
else{
row++;
if(row==n) row=0;
if(column==n) column=0;
MagicSquare[row][column]=s;
row--; column--;
if(row==-1) row+=n;
if(column==-1) column+=n; }
s++;
}
for(i=0;i<n;i++){ for(j=0;j<n;j++)cout<<MagicSquare[i][j]<<"\t";
cout<<"\n\n\n"; }
for(i=0;i<n;i++)delete[] MagicSquare[i];
delete[] MagicSquare; }
else cout<<"N should be odd";
return 0;}

15
2.6 Write a program which implements addition of two polynomials
represented using coefficient-exponent approach discussed in the
class.

#include<iostream>
#include<cstdio>
using namespace std;
void add_poly(int a[],int b[]){
int size1,size2;
size1=a[0];
size2=b[0];
int c[(2*size1)+(2*size2)+1];
int i=1,j=1,count=1,terms=0;
while((i<=2*size1)&&(j<=2*size2)){
if(a[i]<b[j]){
c[count++]=b[j];
c[count++]=b[j+1];
j=j+2;
terms++;
}
else if(a[i]==b[j]){
c[count++]=a[i];
c[count++]=a[i+1]+b[j+1];
i=i+2;
j=j+2;
terms++;
}
else{
c[count++]=a[i];
c[count++]=a[i+1];
i=i+2;
terms++;
}
}
if(i<=(2*size1)-1){
while(i<=(2*size1)-1){
c[count++]=a[i];
c[count++]=a[i+1];
i=i+2;
terms++;
}
}
else if(j<=(2*size2)-1){
while(j<=(2*size2)-1){
c[count++]=b[j];
16
c[count++]=b[j+1];
j=j+2;
terms++;
}
}
c[0]=terms;
cout<<"The addition of two polynomials is:\n";
for(i=1;i<=terms*2;i=i+2){
if(c[i+1]<0) cout<<c[i+1];
else cout<<"+"<<c[i+1];
if(c[i]>0) cout<<"x^"<<c[i];
}
}
int main(){
string p1,p2;//strings to store 2 polynomials
cout<<"Enter the nth degree polynomials to be added\n";
cout<<"polynomial in the form ax^2+bx^1+c , for degree two\n";
cout<<"ax^3+bx^2+cx^1+d , for degree three and so on without
spaces\n";
int count=1,len1,len2;
cout<<"Enter first polynomial: "; cin>>p1;
cout<<"Enter second polynomial: "; cin>>p2;
len1=p1.length();
len2=p2.length();
int first[len1];
int second[len2];
int temp=0,length,i,flag=1;
for(i=0;p1[i]!='\0';i++){
if(p1[i]>47&&p1[i]<58){
temp=temp*10+(p1[i]-48);
if(i>0){
if(p1[i-1]=='-')
flag=-1;
}
}
else{
if(temp!=0){
first[count++]=temp*flag;
temp=0;
flag=1;
}
}
}
first[count++]=temp*flag;
if(count%2==0)
first[count++]=0;
17
length=(count-1)/2;
first[0]=length;
for(i=1;i<count;i=i+2){
int tmp;
tmp=first[i];
first[i]=first[i+1];
first[i+1]=tmp;
}
cout<<"\n";
temp=0;
length=0;
count=1;
flag=1;
for(i=0;p2[i]!='\0';i++){
if(p2[i]>=48&&p2[i]<=57){
temp=temp*10+(p2[i]-48);
if(i>0){
if(p2[i-1]=='-') flag=-1;
}
}
else{
if(temp!=0){
second[count++]=temp*flag;
temp=0;
flag=1;
}
}
}
second[count++]=temp*flag;
if(count%2==0) second[count++]=0;
length=(count-1)/2;
second[0]=length;
for(i=1;i<count;i=i+2){
int tmp;
tmp=second[i];
second[i]=second[i+1];
second[i+1]=tmp;
}
cout<<"\n";
add_poly(first,second);
return 0;
}

18
3.1 Write Implement Stack using one-dimensional array. Write a menu-
driven program with following options :
1. Create a Stack
2. Push an Item
3. Pop an Item
4. Display Stack
5. Exit.

#include<iostream>
using namespace std;
int *p,top=-1,i=0;
void create(){
p=new int [100];
i++;
cout<<"Stack created\n";
}
void push(int element){
if(top==100){
cout<<"error:Stack Overflow!\n";
return;
}
else{
top++;
p[top]=element;
}
}
int pop(){
if(top==-1){
cout<<"error:Stack Underflow!\n";
return -1;
}
else{
int temp=top;
top--;
return p[temp];
}
}
void display(){
if(top==-1){
cout<<"error:Stack is empty\n";
return;
}
else {

19
int temp=top;
while(temp>-1){
cout<<p[temp]<<" ";
temp--;
}
}
}
int main(){
int choice=0,element=0;
char ch='y';
while(choice!=5&&(ch=='y'||ch=='Y')){
cout<<"enter the digit as accordingly:\n";
cout<<"1.to create a Stack\n";
cout<<"2.to push an element to the Stack\n";
cout<<"3.to pop an element from the Stack\n";
cout<<"4.to display the Stack\n";
cout<<"5 to exit\n";
cin>>choice;
switch(choice){
case 1:if(i>0){cout<<"stack already created\n";break;}
else create();
break;
case 2:if(i==0){cout<<"Stack not created!\n"; break;}
cout<<"enter the element to be pushed to the stack:";
cin>>element;
push(element);
break;
case 3:if(i==0){cout<<"Stack not created!\n"; break;}
element=pop();
if(element==-1) break;
cout<<"element poped from the top of the stack is:
"<<element<<"\n";
break;
case 4:if(i==0){
cout<<"Stack not created!\n";
break;}
if(element==-1) break;
cout<<"the stack is: ";display();
break;
case 5:return 0;
default:cout<<"wrong choice!";
}
cout<<"want to continue(y/n): ";cin>>ch;
}
return 0;
}
20
3.2 Write a program which solves the classic Maze problem. A Maze
can be represented as a two-dimensional array with '0'
representing a clear path and '1' representing an obstacle. A (1,1)
index represents the source and (N,N) index represents the target.
Your code must return a path from source to target. The input may
be given as an NxN matrix representing a maze.

#include<iostream>
#include<stack>
using namespace std;
int main(){
int row,col,i,j,r,l,u,d,p,q;
cout<<"\nEnter the dimensions of maze:(number of rows and
columns)";
cin>>row>>col;
int a[row][col];
int visited[row][col];
cout<<"\nAssumptions:";
cout<<"\nEnter 1 for an obstacle and 0 for free path";
cout<<"\nPlease make sure that you enter 0 at
source(indexing 0,0) and at destination (indexing n-1,n-1)\n";
cout<<"\n\nEnter your maze:\n";
for(i=0;i<row;i++){
for(j=0;j<col;j++)
cin>>a[i][j];
}
for(i=0;i<row;i++){
for(j=0;j<col;j++){
if(a[i][j]>1||a[i][j]<0){
cout<<"\nInvalid values entered in the maze.Aborting!";
return -1;
}
}
}
if(a[0][0]==1){
cout<<"\nYou have entered an obstacle at source!Aborting!";
return -1;
}
if(a[row-1][col-1]==1){
cout<<"\nYou have entered an obstacle at destination!Aborting!";
return -1;
}
for(i=0;i<row;i++){
for(j=0;j<col;j++)
21
visited[i][j]=0;
}
stack<int>s1;
i=0;
j=0;
while((i!=row-1)||(j!=col-1)){
r=l=u=d=1;
if(i==0)
u=0;
else if(i==row-1)
d=0;
if(j==0)
l=0;
else if(j==col-1)
r=0;
if(a[i][j+1]==0&&visited[i][j+1]!=-1&&r!=0){
s1.push(i);
s1.push(j);
visited[i][j]=-1;
j=j+1;
}
else if(a[i+1][j]==0&&visited[i+1][j]!=-1&&d!=0){
s1.push(i);
s1.push(j);
visited[i][j]=-1;
i++;
}
else if(a[i-1][j]==0&&visited[i-1][j]!=-1&&u!=0){
s1.push(i);
s1.push(j);
visited[i][j]=-1;
i--;
}
else if(a[i][j-1]==0&&visited[i][j-1]!=-1&&l!=0){
s1.push(i);
s1.push(j);
visited[i][j]=-1;
j--;
}
else{
if(s1.empty()){
cout<<"\nNo path between source and destination found";
return -1;
}
visited[i][j]=-1;
q=s1.top();
22
s1.pop();
p=s1.top();
s1.pop();
i=p;
j=q;
}
}
if(s1.empty()){
cout<<"\nNo path between source and destination found";
return -1;
}
a[row-1][col-1]=2;
while(!s1.empty()){
q=s1.top();
s1.pop();
p=s1.top();
s1.pop();
a[p][q]=2;
}
cout<<"\nNow printing the path:\n(Follow the 2's to find your
way)\n\n";
for(i=0;i<row;i++){
for(j=0;j<col;j++)
cout<<a[i][j]<<" ";
cout<<"\n";
}
return 0;
}

23
3.3 A matrix is called as Sparse if it has many 0 entries (lets roughly
say more than 50% of total elements). Use a memory efficient way
of representing it using an array. Also, write the code for a
transpose operation on it and multiplication of two given sparse
matrices.

#include<iostream>
#include<conio.h>
using namespace std;
class SparseMatrix{
int *a,size,row,col;
public:
SparseMatrix(){
a=NULL;
row=col=size=0;
}
SparseMatrix(int r,int c){
row=r;
col=c;
}
void SparseAlloc(int s){
size=3*s;
a=new int [size];
}
void smArray(int **temp){
int k=0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(temp[i][j]!=0){
a[k++]=i;
a[k++]=j;
a[k++]=temp[i][j];
}
}
}
}
void SparseInput(){
int **temp,s=0;
temp=new int*[row];
for(int i=0;i<row;i++) temp[i]=new int [col];
cout<<"\nEnter sparce matrix:\n";
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cin>>temp[i][j];
24
if(temp[i][j]!=0) s++;
}
}
SparseAlloc(s);
smArray(temp);
for(int i=0;i<row;i++) delete[] temp[i];
delete[] temp;
}
void SparseTranspose(){
int flag;
for(int j=0;j<col;j++){
for(int i=0;i<row;i++){
flag=1;
for(int k=0;k<size;k+=3){
if(a[k]==i&&a[k+1]==j){
cout<<a[k+2]<<" ";
flag=0;
break;
}
}
if(flag) cout<<"0 ";
}
cout<<"\n";
}
}
SparseMatrix multiply(SparseMatrix m){
SparseMatrix ans(row,m.return_col());
int **temp,s=0;
temp=new int*[row];
for(int i=0;i<row;i++) temp[i]=new int [m.return_col()];
for(int i=0;i<row;i++){
for(int j=0;j<m.return_col();j++){
temp[i][j]=0;
for(int k=0;k<col;k++){
for(int l=0;l<size;l+=3){
if(a[l]==i&&a[l+1]==k){
for(int n=0;n<m.return_size();n+=3){
if(m.element(n)==k&&m.element(n+1)==j){
temp[i][j]+=(a[l+2]*m.element(n+2));
s++;
break;
}
}
}
}
}
25
}
}
ans.SparseAlloc(s);
ans.smArray(temp);
for(int i=0;i<row;i++) delete[] temp[i];
delete[] temp;
return ans;
}
void SparseDisplay(){
int k=0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(a[k]==i&&a[k+1]==j){
cout<<a[k+2]<<" ";
k+=3;
}
else
cout<<"0 ";
}
cout<<"\n";
}
}
int return_col(){
return col;
}
int element(int i){
return a[i];
}
int return_size(){
return size;
}
~SparseMatrix(){
delete a;
}
};
int main(){
int row,col,ch;
cout<<"Enter row and column of sparce matrix: ";
cin>>row>>col;
SparseMatrix m1(row,col);
m1.SparseInput();
cout<<"enter the choice accordingly: ";
do{
cout<<"\n1.Display transpose
\n2.Multiply two sparce matrix\n3.Exit";
cout<<"\n\nEnter your choice: ";
26
cin>>ch;
switch(ch)
{
case 1:cout<<"\n\nTranspose of given sparce matrix:\n";
m1.SparseTranspose();
break;
case 2:cout<<"\n\nEnter row and column another sparce matrix: ";
cin>>row>>col;
SparseMatrix m2(row,col);
if(row!=m1.return_col()) cout<<"\n\nNumber of rows are not
valid,i.e.,"<<m1.return_col()<<"!!!";
else{
m2.SparseInput();
SparseMatrix m3=m1.multiply(m2);
cout<<"\n\nResultant matrix:\n";
m3.SparseDisplay();
}
break;
}
if(ch<3){
cout<<"\n\nPress any key to continue...";
getch();
}
} while(ch<3);
return 0;
}

27
3.4 Write a program which evaluates a given postfix arithmetic
expression and converts a postfix expression into an infix
expression.

#include<iostream>
#include<cstring>
using namespace std;
string stk[30];//for expression
int stak[30];//for evaluation of expression
class stack{
int top; //for expression
int etop;//for evaluation of expression
public:
stack(){top=-1; etop=-1;}
void push(string el){//for expression
top++;
stk[top]=el;
}
string pop(){//for expression
top--;
return stk[top+1];
}
void push1(int element){//for evaluation of expression
etop++;
stak[etop]=element;
}
int pop1(){//for evaluation of expression
etop--;
return stak[etop+1];
}
};
int main(){
string exp;//to hold the main postfix expression
stack s;
cout<<"enter a post fix expression: "; cin>>exp;
int i=0;
string a,b,temp;
int m,n;
int operators=0,operends=0;
while(exp[i]!='\0'){
//to convert the expression to infix and evaluate it
temp="";
if(exp[i]=='+'){
28
operators++;
a=s.pop(); b=s.pop(); temp="("+b+"+"+a+")"; s.push(temp);//for
expression
m=s.pop1(); n=s.pop1(); s.push1(m+n);}
//for evaluation of expression
else if(exp[i]=='-'){
operators++;
a=s.pop(); b=s.pop(); temp="("+b+"-"+a+")"; s.push(temp);//for
expression
m=s.pop1(); n=s.pop1(); s.push1(n-m);}
//for evaluation of expression
else if(exp[i]=='/'){
operators++;
a=s.pop(); b=s.pop(); temp="("+b+"/"+a+")"; s.push(temp);
//for expression
m=s.pop1(); if(m==0)break; n=s.pop1(); s.push1(n/m);}//for
evaluation of expression
else if(exp[i]=='*'){
operators++;
a=s.pop(); b=s.pop(); temp="("+b+"*"+a+")"; s.push(temp);
//for expression
m=s.pop1(); n=s.pop1(); s.push1(m*n);}
//for evaluation of expression
else if(exp[i]=='%'){
operators++;
a=s.pop(); b=s.pop(); temp="("+b+"%"+a+")"; s.push(temp);
//for expression
m=s.pop1(); n=s.pop1(); s.push1(n%m);}
//for evaluation of expression
else{
operends++;
temp+=exp[i]; s.push(temp);//for expression
s.push1(exp[i]-48);}//for evaluation of expression
i++;
}
if(operators+1!=operends){
cout<<"wrong expression!";
return -1;
}
cout<<"the infix expression is: "<<s.pop();
cout<<"\nthe evaluated expression is: "<<s.pop1();
return 0;
}

29
4.1 Write a program to implement singly linked list. Implement a menu-
driven program consists of following options:
1. Insert at front
2. Insert at last
3. Delete from front
4. Delete from last
5. Invert a list
6. Display list
7. Exit.

#include<iostream>
using namespace std;
class node{
node *next;
int data;
friend class SinglyLinkedList;
};
class SinglyLinkedList{
node *head;
public:
SinglyLinkedList(){
head=0;
}
void InsertAtFront(int val){
if(head==0){
head=new node;
head->next=0;
head->data=val;
}
else{
node *temp=new node;
temp->next=head;
temp->data=val;
head=temp;}
}
void InsertAtLast(int val){
if(head==0){
head=new node;
head->next=0;
head->data=val;
}
else{
node *temp=new node;
node *temp1=head;
temp->next=0;
temp->data=val;
while(temp1->next!=0) temp1=temp1->next;
temp1->next=temp;}
}

30
int DeleteFromhead(){/*for no element present*/
if(head==0){
return -1;
}
else if(head->next==0){/*for only one element present*/
int i=head->data;
delete head;
head=0;
return i;
}
else{/*for more than one element present*/
node *temp=head;
head=head->next;
int i=temp->data;
delete temp;
return i;
}
}
int DeleteFromLast(){/*for no element present*/
if(head==0){
return -1;
}
else if(head->next==0){/*for no element present*/
int i=head->data;
delete head;
head=0;
return i;
}
else{/*for more than one element present*/
node *temp=head;
while(temp->next->next!=0) temp=temp->next;
node *temp1=temp->next;
temp->next=0;
int i=temp1->data;
delete temp1;
return i;
}
}
void InvertList(){
if(head==0) cout<<"List empty";/*for no element present*/
else if(head->next==0) cout<<"List inverted";/*for inly one element
present*/
else{
node *current=head;
node *previous=0;
node *temp=previous;
while(current!=0){
previous=current;
current=current->next;
previous->next=temp;
temp=previous;

31
}
head=previous;
cout<<"Inverted ";
DisplayList(); }
}
void DisplayList(){
if(head==0) cout<<"List empty";
else if(head->next==0) cout<<"Linked list: "<<head->data;
else{
node *temp=head;
cout<<"Linked list: "<<temp->data<<"->";
while(true){
temp=temp->next;
cout<<temp->data;
if(temp->next==0) break;
cout<<"->"; }
}}
};
int main(){
SinglyLinkedList *SLL=new SinglyLinkedList;
int optn=0,element=0;
cout<<"\n1. Insert an element at the head of the list";
cout<<"\n2. Insert an element at the end of the list";
cout<<"\n3. Delete an element from the head of the list";
cout<<"\n4. Delete an element from the end of the list";
cout<<"\n5. Invert the list";
cout<<"\n6. Display the list";
cout<<"\n7. Exit";
while(true){
cout<<"\nEnter the operation to be performed: "; cin>>optn;
switch(optn){
case 1:cout<<"Enter the element to be inserted at head of the list:
";cin>>element;
SLL->InsertAtFront(element); break;
case 2:cout<<"Enter the element to be inserted at the end of the list:
";cin>>element;
SLL->InsertAtLast(element); break;
case 3:element=SLL->DeleteFromhead();
if(element!=-1)
cout<<"The element deleted from the head of the list: "<<element<<"\n";
else cout<<"List empty"; break;
case 4:element=SLL->DeleteFromLast();
if(element!=-1)
cout<<"The element deleted from the end of the list: "<<element<<"\n";
else cout<<"List empty"; break;
case 5:SLL->InvertList();
cout<<"\n"; break;
case 6:SLL->DisplayList();
cout<<"\n"; break;
case 7:while(SLL->DeleteFromhead()!=-1) delete SLL; return 0;
default:cout<<"enter correct choice\n"; } }

32
return 0;}
4.2 Write a program in C++ to implement a circular queue which
can store n elements. Implement the following operations:
1. Create
2. Insert
3. Delete
4. Display

#include<iostream>
using namespace std;
short int flag=0;
class CircularQueue{//class implementing circular queue as array
int *queue; //array of the queue being implemented
int capacity;//capacity of queue
int front,rear;//front and rear of the queue being implemented
public:
CircularQueue(){
//constructor for initializing both front and rear as zero
front=rear=0;
}
void Create(int n){
capacity=n+1;
queue=new int[capacity];
flag=1; //queue will be created only once during a program run
cout<<"Queue created\n";
}
void Insert(int el){
if(flag==0){ cout<<"No queue created"; return;}
else if(front==((rear+1)%capacity))
cout<<"Queue full, "<<el<<" was not added to the queue\n";
else{
rear=(rear+1)%capacity;
queue[rear]=el;
}
}
int Delete(){
//deleting an element from the queue as according to the algorithm
if(flag==0){ cout<<"No queue created"; return-100;}
else if(front==rear){
cout<<"Queue empty\n";
return -100;
}
else{
front=(front+1)%capacity;
return queue[front];
}
}
void Display(){//display the queue from front to read, in order
33
if(flag==0){ cout<<"No queue created";return;}
else if(front==rear){
cout<<"Queue empty\n";
return;
}
else{
int temp=front;
cout<<"Queue:";
while(temp!=rear){
temp=(temp+1)%capacity;
cout<<" "<<queue[temp];
}
cout<<"\n";
}
}
};
int main(){
CircularQueue CQ;
short int optn=0;
int element=0;
cout<<"\n1. Create the circular queue";
cout<<"\n2. Insert an element in the circular queue";
cout<<"\n3. Delete an element from the circular queue";
cout<<"\n4. Display the circular queue";
cout<<"\n5. Exit";
while(true){
cout<<"\nEnter the operation to be performed: "; cin>>optn;
switch(optn){
case 1:if(flag==1) cout<<"Queue already created";
else{
cout<<"Enter the size of the circular queue to be created:
";cin>>element;
CQ.Create(element);
}
break;
case 2:
cout<<"Enter the element to be inserted in the circular queue: ";
cin>>element;
CQ.Insert(element);
break;
case 3:element=CQ.Delete();
if(element!=-100)
cout<<"The element deleted from the circular queue: "<<element;
break;
case 4:CQ.Display();
break;
case 5:return 0;
default:cout<<"enter correct choice\n";
}
}
return 0;

34
}
4.3 Implement Polynomial addition using linked list.

#include<iostream>
using namespace std;
short index=1;
struct node{//definition of node to store a polynomial
int number;//the coefficient of X
int exponent;//corresponding power of X
node *next; //link to next node
};
void Insert(int n,int e,node *&head){//function to insert the values at end of
list
if(head==0){//if the list is empty
head=new node;
head->next=0;
head->number=n;
head->exponent=e;
}
else{//if list has more than zero nodes
node *temp=new node;
node *temp1=head;
temp->next=0;
temp->number=n;
temp->exponent=e;
while(temp1->next!=0) temp1=temp1->next;
temp1->next=temp;}
}
class PolynomialAddition{//class which accomplishes the addition of 2
polynomials
node *polynomial;//stores the polynomial
node *sum;//stores the polynomials, here 2
public:
PolynomialAddition(){polynomial=0; sum=0;}//constructor to initialize
polynomial=0 & sum=0
void GetPolynomial();//function to get the polynomial in form of string and
store it in the list
void operator+(const PolynomialAddition &);
//overloaded '+' operator to perform addition of polynomials
void DisplaySum(){//to display the sum of the polynomials, here 2
node*temp=sum;
cout<<"Sum of the polynomials: ";
char ch;
while(temp!=0){
ch=(temp->number>=0)?' +':' ';
cout<<ch<<temp->number<<"X^"<<temp->exponent;
temp=temp->next;}
}
};
void PolynomialAddition::GetPolynomial(){
string p;
int temp=0,flag=1,i;
35
cout<<"Enter polynomial "<<index++<<": ";cin>>p;
int len=p.length();
int count=0;
int *poly=new int[len];
for(i=0;i<len;i++){
if(p[i]>47&&p[i]<58){
temp=temp*10+(p[i]-48);
if(i>0){
if(p[i-1]=='-')
flag=-1;
}
}
else{
if(temp!=0){
poly[count++]=temp*flag;//polynomial being stored in an array poly
temp=0;//with coefficient of X at even index and exponent at odd index
flag=1;
}
}
}
poly[count++]=temp*flag;
if(count%2==1) poly[count++]=0;//adding the last element i1 element with
exponent=0
for(i=0;i<count;i+=2) Insert(poly[i],poly[i+1],polynomial);
delete []poly;
}
void PolynomialAddition::operator+(const PolynomialAddition &b){
node* a1=polynomial; //list to store first polynomial
node* b1=b.polynomial;//list to store second polynomial
while(a1&&b1){
if(a1->exponent==b1->exponent){ Insert(a1->number+b1->number,b1-
>exponent,sum);
a1=a1->next; b1=b1->next;
}
else if(a1->exponent<b1->exponent){ Insert(b1->number,b1->exponent,sum);
b1=b1->next;
}
else{ Insert(a1->number,a1->exponent,sum);
a1=a1->next;}
}
while(a1){Insert(a1->number,a1->exponent,sum);
a1=a1->next;
}
while(b1){ Insert(b1->number,b1->exponent,sum);
b1=b1->next; }
}
int main(){
cout<<"...POLYNOMIAL ADDITION...\n";
PolynomialAddition a,b;
a.GetPolynomial();
b.GetPolynomial();
a+b;//call to the overloaded operator+
a.DisplaySum();
return 0;}
36
4.4 Implement following dynamic memory management functions using
linked list :
1. First fit
2. Best fit
3. Worst fit

#include<iostream>
#include<fstream>
using namespace std;
struct node{
int data;
node *next;
};
void Insert(int n,node *&head){//function to insert the values at end of list
if(head==0){//if the list is empty
head=new node;
head->next=0;
head->data=n;
}
else{//if list has more than zero nodes
node *x=head;
while(x->next!=0) x=x->next;
x->next=new node;
x=x->next;
x->next=0;
x->data=n;
}
}
void DeleteNode(node *&head,node *&temp){//function to delete a particular node
from list
if(head==temp){//takes the list and the pointer to the node to be deleted as
the argument
head=head->next;
delete temp;
}
else{
node *x=head;
while(x!=0){
if(x->next==temp){
x->next=temp->next;
delete temp;
break;
}
x=x->next;
}
}
}
void putFile(int temp,node *&head){//function to put the lists in the file
ofstream fout; //takes the required memory and the list as
the argument
fout.open("final.txt",ios::app|ios::out);
fout<<temp<<": ";
37
if(head==0)fout<<"Nothing alloted, insufficient memory";
else{
node *temp1=head;
while(temp1!=0){
fout<<temp1->data<<" ";
temp1=temp1->next;
}
}
fout<<endl;
fout.close();
}
class MemoryManagement{
node *list=0;
node *fFit=0;//list for applying first fit algorithm
node *bFit=0;//list for applying best fit algorithm
node *wFit=0;//list for applying worst fit algorithm
public:
void initialize(){
ifstream f;
f.open("request.txt");
//contains the data for he memory list to be created
int i=0;
while(!f.eof()){
f>>i;
Insert(i,list);//the main list of the memory
Insert(i,fFit);
Insert(i,bFit);
Insert(i,wFit);
}
f.close();
}

void FirstFit(int);//function to apply first fit algorithm


void BestFit(int);//function to apply best fit algorithm
void WorstFit(int);//function to apply worst fit algorithm

void put(){//to put the original list to the file


node *temp=list;
ofstream fout;
fout.open("final.txt",ios::app|ios::out);
fout<<"Original List: ";
while(temp!=0){
fout<<temp->data<<" ";
temp=temp->next;
}
fout<<endl;
fout.close();
}
};
void MemoryManagement::FirstFit(int rMemory){
//rMemory is the required memory to be alloted
node *temp=fFit;
while(temp!=0){
if(rMemory==temp->data){
38
DeleteNode(fFit,temp);
putFile(rMemory,fFit);
return;
}
else if(temp->data>rMemory){
temp->data-=rMemory; putFile(rMemory,fFit);
return;}
else temp=temp->next;
}
temp=0;
putFile(rMemory,temp);
}
void MemoryManagement::BestFit(int rMemory){
node *temp=bFit;
int min;
while(temp!=0){
if(temp->data>=rMemory){
min=temp->data;
break;
}
else temp=temp->next;
}
while(temp!=0){
if(temp->data==rMemory){
DeleteNode(bFit,temp);
putFile(rMemory,bFit);
return;
}
else if(temp->data>rMemory){
if(min>(temp->data-rMemory)) min=temp->data-rMemory;
}
temp=temp->next;
}
temp=bFit;
while(temp!=0){
if((temp->data)==(rMemory+min)){
temp->data=min;
putFile(rMemory,bFit);
return;
}
temp=temp->next;
}
temp=0;
putFile(rMemory,temp);
}
void MemoryManagement::WorstFit(int rMemory){
node *temp=wFit;
int max;
max=wFit->data;
temp=temp->next;
while(temp!=0){
if(temp->data>max) max=temp->data;
temp=temp->next;
}
39
temp=wFit;
while(temp!=0){
if(temp->data==max){
if(rMemory==max){
DeleteNode(wFit,temp);
putFile(rMemory,wFit);
return;
}
else if(max>rMemory){
temp->data-=rMemory;
putFile(rMemory,wFit);
return;
}
}
temp=temp->next;
}
temp=0;
putFile(rMemory,temp);
}
int main(){
ifstream fin;
ofstream fout;
int temp;
MemoryManagement m;
m.initialize();
m.put();

fin.open("freelist.txt");
fout.open("final.txt",ios::app|ios::out);
fout<<"\nFirst Fit:\n";
fout.close();
while(!fin.eof()){
fin>>temp;
m.FirstFit(temp);
}
fin.close();
fin.open("freelist.txt");
fout.open("final.txt",ios::app|ios::out);
fout<<"\nBest Fit:\n";
fout.close();
while(!fin.eof()){
fin>>temp;
m.BestFit(temp);
}
fin.close();
fin.open("freelist.txt");
fout.open("final.txt",ios::app|ios::out);
fout<<"\nWorst Fit:\n";
fout.close();
while(!fin.eof()){
fin>>temp;
m.WorstFit(temp);
}
fin.close();
40
return 0;
}

//Includes 2 files:

request.txt and freelist.txt

Contents of freelist.txt:

100
123
88
560
700
300

Contents of request.txt:

200
300
100
500
600
120
450
666

41
4.5 Write a program to find the equivalence of a class based on given
equivalence relations.

#include<iostream>
#include<fstream>
using namespace std;
short classno=1;
struct node{
int data;
node* next;
};
void InsertAtFront(int n,node* &head){
node* x=new node;
x->data=n;
x->next=head;
head=x;
}
class EquivalenceClass{
node **first;
bool *out;
public:
void Equivalence();
};
void EquivalenceClass::Equivalence(){
ifstream f;
f.open("input.txt",ios::in);
int n,i,j;
f>>n;
first=new node*[n];
out=new bool[n];
for(i=0;i<n;i++){
first[i]=0;
out[i]=false;
}
while(!f.eof()){
f>>i>>j;
InsertAtFront(i,first[j]);
InsertAtFront(j,first[i]);
}
f.close();
ofstream fout;
fout.open("output.txt",ios::app|ios::out);
for(i=0;i<n;i++){
if(!out[i]){
fout<<endl<<"Class "<<classno++<<": "<<i;
out[i]=true;
node *x=first[i],*top=0;
while(1){
while(x){
j=x->data;
if(!out[j]){
fout<<", "<<j;
42
out[j]=true;
node *y=x->next;
x->next=top;
top=x;
x=y;
}
else x=x->next;
}
if(!top) break;
x=first[top->data];
top=top->next;
}
}
}
fout.close();
delete []first;
delete []out;
}
int main(){
EquivalenceClass EC;
EC.Equivalence();
return 0;
}

//Includes a file:

input.txt

Contents of input.txt:

12
0 4
3 1
6 10
8 9
7 4
6 8
3 5
2 11
11 0

43
5.1 Write a program to solve the Tower of Hanoi problem for N
disks using recursion. Report the no. of disks for which your
code exhausts stack memory.

#include<iostream>
using namespace std;
void MoveDisc(int source,int target){
static int temp=1;
cout<<temp++<<".Move from "<<source<<" to "<<target<<"\n";
}
void MoveTower(int n,int source,int target,int spare){
if(n>=1){
MoveTower(n-1,source,spare,target);
MoveDisc(source,target);
MoveTower(n-1,spare,target,source);
}
}
int main(){
int target,source,spare,N;
cout<<"Enter the number of discs: "; cin>>N;
cout<<"Enter source(1/2/3): "; cin>>source;
cout<<"Enter target(1/2/3): "; cin>>target;
if(source==1&&target==2) spare=3;
else if(source==2&&target==1)
spare=3;
else if(source==1&&target==3)
spare=2;
else if(source==3&&target==1) spare=2;
else if(source==2&&target==3)
spare=1;
else if(source==3&&target==2)
spare=1;
MoveTower(N,source,target,spare);
return 0;
}

44
5.2 Write Implement in C++ merge sort algorithm for a given array.

#include<iostream>
using namespace std;
void merge(int*,int,int,int);
void mergesort(int *a,int low,int high){
int mid;
if(low<high){ mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,high,mid);
}
return;
}
void merge(int *a,int low,int high,int mid){
int i,j,k,c[50];
i=low;
k=low;
j=mid+1;
while(i<=mid&&j<=high){
if(a[i]<a[j]){
c[k]=a[i++];
k++;
}
else{
c[k] = a[j++];
k++;
}
}
while(i<=mid){
c[k]=a[i++];
k++;
}
while(j<=high){
c[k]=a[j++];
k++;
}
for(i=low;i<k;i++) a[i]=c[i];
}
int main(){
int *a,i,n;
cout<<"enter the size of array: ";cin>>n;
a=new int[n];
cout<<"enter the elements: ";
for(i=0;i<n;i++) cin>>a[i];
mergesort(a,0,n-1);
cout<<"sorted array: ";
for(i=0;i<n;i++) cout<<a[i]<<" ";
delete a;
return 0;
}

45
5.3 Implement Quick Sort algorithm using in-place sorting approach.

#include<iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void QuickSort(int array[],int a,int b){
if(a>=b) return;
int l=a,r=b-1,p=array[b];
while(l<=r)
{
while(l<=r&&array[l]<=p) l++;
while(l<=r&&array[r]>=p) r--;
if(l<r) swap(array[l],array[r]);
}
swap(array[l],array[b]);
QuickSort(array,a,l-1);
QuickSort(array,l+1,b);
}

int main()
{
int i,N;
cout<<"Enter the number of elements in the array(>=1): ";
cin>>N;
int *array=new int[N];
cout<<"Enter the array: ";
for(i=0;i<N;i++) cin>>array[i];
QuickSort(array,0,N-1);
cout<<"Sorted array:\n";
for(i=0;i<N;i++) cout<<array[i]<<" ";
return 0;
}

46
5.4 Implement a binary heap as follows :
a. Use build_max_heap() function to construct maxheap for
given n numbers.
b. Implement Priority Queue by implementing insert() and
extract_max() function.
c. Extend the above implementation to support heap sort
algorithm.

#include<iostream>
using namespace std;
int largest;
class BinaryHeap{
protected:
int heap[50];
int heap_size;
public:
BinaryHeap(){}
BinaryHeap(int n){
heap_size=n;
cout<<"Enter "<<heap_size<<" numbers: ";
for(int i=1;i<=heap_size;i++) cin>>heap[i];
build_max_heap();
}
void max_heapify(int i){
int l=2*i;
int r=2*i+1;
if(l<=heap_size&&heap[l]>=heap[i]) largest=l;
else largest=i;
if(r<=heap_size&&heap[r]>=heap[largest]) largest=r;
if(largest!=i){
heap[i]+=heap[largest]; heap[largest]=heap[i]-heap[largest]; heap[i]-
=heap[largest];
max_heapify(largest);
}
}
void build_max_heap(){
for(int i=heap_size/2;i>0;i--) max_heapify(i);
}
void show_heap(){
cout<<"Binary heap: ";
for(int i=1;i<=heap_size;i++) cout<<heap[i]<<" ";
cout<<"\n";
}
void insert_heap(){
int e;
cout<<"enter the element to be inserted: ";cin>>e;
heap[++heap_size]=e;
build_max_heap();
show_heap();
}
47
int extract_max(){
int max=heap[1];
heap[1]=heap[heap_size--];
build_max_heap();
return max;
}
};
class HeapSort:public BinaryHeap{
public:
HeapSort(){}
void heap_sort(){
int i;
cout<<"Enter the size of array to be sorted: ";
cin>>heap_size;
int n=heap_size;
cout<<"Enter the array to be sorted: ";
for(i=1;i<=heap_size;i++) cin>>heap[i];
build_max_heap();
int l=heap_size;
for(i=l;i>1;i--){
heap[i]+=heap[1]; heap[1]=heap[i]-heap[1]; heap[i]-=heap[1];
heap_size--;
max_heapify(1);
}
cout<<"Sorted array: ";
for(int i=1;i<=n;i++) cout<<heap[i]<<" ";
delete heap;
}
};
int main(){
int n;
cout<<"Enter the size of the binary heap: ";cin>>n;
BinaryHeap b(n);
b.show_heap();
cout<<"Implementation of binary heap\n";
cout<<"1.insert into heap\n";
cout<<"2.extract max form the heap\n";
cout<<"3.exit\n";
int flag=1,e=0;
while(flag==1){
cout<<"Enter choice: "; cin>>n;
switch(n){
case 1:b.insert_heap(); break;
case 2:cout<<"max extracted element: "<<
b.extract_max();
b.show_heap(); break;
case 3:flag=0;
}
}
HeapSort h;
cout<<"Heap sort:\n"; h.heap_sort();
return 0;
}

48
5.5 Write a menu driven program to implement Binary Search Tree
(BST) using following functions :
insert() function adds key into BST
search() function searches a key in BST
inorder(),preorder() and postorder() traversal to display BST in
different way.

#include<iostream>
using namespace std;
class BSTnode{
int key;
BSTnode *left;
BSTnode *right;
friend class BinarySearchTree;
};
class BinarySearchTree{
BSTnode *BST;
public:
BinarySearchTree(){
BST=0;
}
BSTnode *root(){
return BST;
}
void insert(int element){
if(BST==0){
BST=new BSTnode;
BST->left=0;
BST->right=0;
BST->key=element;
}
else{
BSTnode *temp1=BST,*temp2=BST;
int flag=0;
while(temp1!=0){
if(element>temp1->key){
temp2=temp1;
temp1=temp1->right;
flag=1;
}
else if(element<=temp1->key){
temp2=temp1;
temp1=temp1->left;
flag=0;
49
}
}
if(flag==1){
temp2->right=new BSTnode;
temp2=temp2->right;
temp2->left=0;
temp2->right=0;
temp2->key=element;
}
else{
temp2->left=new BSTnode;
temp2=temp2->left;
temp2->left=0;
temp2->right=0;
temp2->key=element;
}
}
}
bool search(int k){
BSTnode *temp=BST;
while(temp!=0){
if(k>temp->key) temp=temp->right;
else if(k<temp->key) temp=temp->left;
else return true;
}
return false;
}
void inorder(BSTnode *temp){
if(temp){
inorder(temp->left);
cout<<temp->key<<" ";
inorder(temp->right);
}
else return;
}
void preorder(BSTnode *temp){
if(temp){
cout<<temp->key<<" ";
preorder(temp->left);
preorder(temp->right);
}
else return;
}
void postorder(BSTnode *temp){
50
if(temp){
postorder(temp->left);
postorder(temp->right);
cout<<temp->key<<" ";
}
else return;
}
};
int main(){
int i=0,el;
BinarySearchTree b;
cout<<"1. Insert an element to BST\n";
cout<<"2. Search for an element to BST\n";
cout<<"3. Inorder traversal of BST\n";
cout<<"4. preorder traversal of BST\n";
cout<<"5. postorder traversal of BST\n";
cout<<"6. Exit\n";
while(true){
cout<<"enter the operation to be performed: "; cin>>i;
switch(i){
case 1:cout<<"Enter the element to be inserted to BST:
";cin>>el;
b.insert(el);
break;
case 2:cout<<"Enter the element to be searched in BST:
";cin>>el;
if(b.search(el)) cout<<"element present\n";
else cout<<"element not present\n";
break;
case 3:cout<<"Inordertraversal:";
b.inorder(b.root());cout<<"\n";
break;
case 4:cout<<"Preorder traversal: ";
b.preorder(b.root());cout<<"\n";
break;
case 5:cout<<"Postordertraversal:";
b.postorder(b.root());cout<<"\n";
break;
case 6:return 0;
default: cout<<"enter correct choice\n";
}
}
return 0;
}
51

Vous aimerez peut-être aussi