0% found this document useful (0 votes)
31 views52 pages

OOPS and Data Structures Lab Guide

Uploaded by

Sasi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views52 pages

OOPS and Data Structures Lab Guide

Uploaded by

Sasi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EXCEL ENGINEERING COLLEGE

(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University,
Chennai Accredited by NBA, NAAC with “A+” and Recognised
by UGC (2f &12B)
KOMARAPALAYAM – 637303

DEPARTMENT OF BIOMEDICAL ENGINEERING

23CS310-OBJECT ORIENTED PROGRAMMING


AND DATA STRUCTURE

III SEMESTER - R 2023

PREPARED BY

[Link] AP/BME

[Link] AP/BME
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

1. To provide fundamental knowledge to formulate, solve and analyze engineering

problems and pursue higher studies.


2. To develop the ability of the students in comprehending, analyzing and synthesizing

data in order to design software and create novel software systems.


3. To inculcate effective communication skills, team skills, professional and ethical

attitude in the students for enabling them to relate engineering issues with social
issues in a broader context.
4. To provide students managerial and leadership skills so as to make them successfully

employed and to demonstrate a pursuit of lifelong learning in multidisciplinary


environment.
PROGRAMME OUTCOMES (POs)

5. Engineering Knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals and an engineering specialization to the solution of
complex engineering problems.
6. Problem Analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
7. Design / Development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
8. Conduct investigations of complex problems: Use research-based knowledge
and research methods, including design of experiments, analysis and interpretation
of data, and synthesis of the information to provide valid conclusions.
9. Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling of
complex engineering activities with an understanding of the limitations.
10. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
11. Environment and Sustainability: Understand the impact of the professional
engineering solutions to societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
12. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
13. Individual and team work: Function effectively as an individual and as a member
or leader in diverse teams, and in multidisciplinary settings.
14. Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
15. Project management and finance: Demonstrate knowledge and understanding of
the engineering management principles and apply these to one’s own work, as a
member and laddering team, to manage projects and in multi-disciplinary
environments.
16. Lifelong learning: Recognize the need for and have the preparation and ability to
engage in independent and lifelong learning in the broadest context of
technological change.
Excel Engineering College
Department of Biomedical Engineering
Sub Code/ Name : 23CS310/OOPS AND DATA STRUCTURES LABORATORY
Semester / Year : II/ III
Academic Year : 2024 - 25
Batch : 2023 - 2027
INDEX
Exper
iment Date Name of the Experiment Marks Signature
No.
Develop simple program in C++
1 Using Control Structures

Implement Constructers and Destructors


2
in C++.

Build a C++ program with member


3 function and friend function in C++.

Write a C++ program to use pointer for


4 both base and derived classes and call the
member function
Write C++ program to demonstrate
operator overloading
5
Make use of Inheritance in c++
application
6
Build a c++ program to perform list
7 operators using linked list
Construct a c++ program to perform
8 stack operation using array

Develop a C++ application to perform


9 insertion sort, quick sort and merge soft.
Write a C++ programs to implement
10 recursive and non recursive i) Linear
search ii) Binary search
LIST OF EXPERIMENT

1. Develop simple program in C++ Using Control Structures

2. Implement Constructors and Destructors in C++.

3. Build a C++ program with member function and friend function in C++.

4. Write a C++ program to use pointer for both base and derived classes and call
the member function
5. Write C++ program to demonstrate operator overloading.

6. Make use of Inheritance in C++ application

7. Build a C++ program to perform list operators using linked list.

8. Construct a C++ program to perform stack operation using array

9. Develop a C++ application to perform insertion sort, quick sort and merge soft.

10. Write a C++ programs to implement recursive and non recursive i) Linear
search ii) Binary search
[Link]
Develop simple program in C++ Using Control Structure

Aim:

To develop simple programs in C++ using Control statements.

Algorithm:

1. Start the program.


2. Read the value of a,b.
3. If a greater than b,print the first number is biggest.
4. Else,Print second number is biggest.
5. Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
cout<<”Enter the first
number”; cin>>a;
cout<<”Enter the second
number”; cin>>b;
if(a>b)
{

}
cout<<”The biggest number is”<<a;

else
cout<<”The biggest number is”<<b;
7
return 0;
}

Output:

Enter the first number

15 Enter the second

number 30 The biggest

number is 30

Result:
Thus the program in C++ using Control statements was verified and output
was verified successfully.

8
[Link]
Implement Constructors and Destructors in C++

Aim:
To write a program to generate Constructors and Destructors in C++

Algorithm:

Step 1: Define the Class

 Start by defining your class with private data members and public member functions.

Step 2: Implement Constructors

 Default Constructor

Step 3: Implement Destructor

 Implement the destructor to clean up resources used by the object. Here, it doesn’t need to
do much since std::vector handles its own memory management.

Step 4: Implement Member Function

 Implement any additional member functions as needed. Here, performOperation() is a


placeholder to perform some algorithmic operation.

Step 5: Test in main() Function

 Write a main() function to create instances of Algorithm and test the constructors and
destructor.

Program

#include <iostream>
#include <string>

class Person {
private:
std::string name;
int age;

public:
9
// Default Constructor
Person() {
name = "Unknown";
age = 0;
std::cout << "Default Constructor called" << std::endl;
}

// Parameterized Constructor
Person(std::string n, int a) {
name = n;
age = a;
std::cout << "Parameterized Constructor called with Name: " << name << ", Age: " << age
<< std::endl;
}

// Copy Constructor
Person(const Person& p) {
name = [Link];
age = [Link];
std::cout << "Copy Constructor called to create a copy of " << [Link] << std::endl;
}

// Destructor
~Person() {
std::cout << "Destructor called for " << name << std::endl;
}

void display() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};

int main() {
std::cout << "Creating objects:" << std::endl;
std::cout << "-----------------" << std::endl;

Person p1; // Default Constructor called


[Link]();
std::cout << std::endl;

Person p2("Alice", 30); // Parameterized Constructor called


[Link]();
std::cout << std::endl;
10
Person p3 = p2; // Copy Constructor called
[Link]();
std::cout << std::endl;

std::cout << "Exiting scope, destructors will be called automatically:" << std::endl;
std::cout << "-------------------------------------------------------" << std::endl;

return 0;
}

11
Output

Creating objects: -----------------


Default Constructor called Name: Unknown, Age: 0
Parameterized Constructor called with Name: Alice, Age: 30 Name: Alice, Age: 30

Copy Constructor called to create a copy of Alice Name: Alice, Age: 30 Exiting scope,

destructors will be called automatically:

Destructor called for Alice


Destructor called for Alice
Destructor called for Unknown

Result
Thus the program to generate Constructors and Destructors in C++ was
executed and output verified successfully.
12
[Link]
Build a C++ program with member function and friend function in
C++.

Aim:
To write a C++ program for implementing the member function friend function.
Algorithm:
1. Start the program
2. Define a class box.
3. Define the friend function with different arguments with different data types.
4. Define the object for the class Box in main function.
5. Call the friend function.
6. Print the output.
7. Stop the program.

Program:
#include<iostream.h>
#include<conio.
h> class Box
{
private:
int
length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
[Link] +=
10; return
[Link];
13
}
int main()
{
Box b;
cout<<"Length of box: "<<
printLength(b)<<endl; return 0;
}

14
Output:

Length of box: 10

Result:
Thus the C++ program for implementing the member function and friend function
was executed and output verified successfully.

15
[Link] Write C++ program to demonstrate operator overloading.

Aim:
To write a C++ program for implementing the function overloading.

Algorithm:
1. Define a class test.
2. Define the function sum with different arguments with different data types.
3. Define the object for the class test in main function.
4. Call the function using the argument type to perform different operations.
5. Print the output.

Program:
#include<iostream.
h>
#include<conio.h
> class test
{
public:
int sum(int,int);
float sum(float,float);
double
sum(double,double); }; int
test::sum(int a, int b)
{
return(a+b);
}
float test::sum(float a ,float b)
{
return(a+b);
}
double test::sum(double a, double b)
{
return(a+b);
16
}
void main()
{
test obj;
int
choice,ans;
int a,b;
float x,y;
double m,n; double result=0;
clrscr();
cout<<"\n\t\t main menu";
cout<<"\n\t1. Addition of two integer
numbers"; cout<<"\n\t2. Addition of two
float numbers"; cout<<"\n\t3. Addition of
two double numbers"<<endl; do
{
cout<<"\n enter your
choice:"; cin>>choice;
switch(choice)
{
case 1: cout<<"\n enter 2
numbers"; cin>>a>>b;
result=[Link](a,b
); break;
case 2:
cout<<"\n enter 2
number"; cin>>x>>y;
result=[Link](x,y);
break;
case 3:
cout<<"\n enter 2
number";
cin>>m>>n;
result=[Link](m,n);
break;
default:
cout<<"wrong choice";
17
break;
}
cout<<"\n\n
result"<<result<<endl;
cout<<"\ndo you want to
continue:"; ans=getch();
}
while(ans=='y'||ans=='Y');
getch();
}

18
Output:
Main menu
Addition of two integer
numbers Addition of two
float numbers Addition of
two double numbers enter
your choice 1
enter 2 number 2 3
result 5
do you want to
continue: y enter your
choice 2
enter 2 number 1.13 5.6
result 6.73
do you want to
continue: y enter your
choice 3
enter 2 number 345 354
result 699
do you want to continue: n

Result:
Thus the C++ program for function Overloading was created, executed and output
was verified successfully.
19
[Link]
Write a C++ program to use pointer for both base and
derived classes and call the member function

Aim:
To write a program in C++ to use pointer for both base and derived classes and
call the member function
Algorithm:

1. Define the Base Class Shape

2. Define the Derived Class Rectangle

[Link] Pointers to Objects

In main(), create objects using pointers to both Shape and Rectangle, and call the calculateArea()
function.

Program:

include <iostream> //
Base class class Shape
{
public: // Virtual function to calculate area virtual
void calculateArea()
{
std::cout << "Calculating area of Shape" << std::endl; }
};

Derived class class Rectangle :


public Shape
{
private: int length; int width; public: Rectangle(int l, int w) : length(l), width(w) {} //
Override calculateArea() to calculate area of rectangle void calculateArea()
override
{
int area = length * width; std::cout << "Area of Rectangle: " << area << std::endl; }

20
}:

int main()
{
// Pointer to base class Shape* shapePtr;
// Pointer to derived class Rectangle rect(5, 10);
shapePtr = &rect; // Call calculate Area() using base class pointer shapePtr->calculateArea();
return 0;
}

21
Output:

Result:
Thus the C++ program for implementation of classes and objects was created,
executed and output was verified successfully.

22
[Link]
Make use of Inheritance in C++ application

Aim:
To write a C++ program for implementing the inheritance.

Algorithm:

1. Start the process.


2. Define the base class with variables and functions.
3. Define the derived class with variables and functions.
4. Get two values in main function.
5. Define the object for derived class in main function.
6. Access member of derived class and base class using the derived class object.
7. Stop the process.

Program:
#include<iostream.
h>
#include<conio.h
> class base
{
public:
int x;
void set_x(int )
{
x=n;
}void show_x()
{

23
cout<<”\n\t Base
class….”;
cout<<”\n\tx=”<<x;
}};

class derived:public base


{
int y;
public:
void set_y(int n)
{
y=n;
}void show_xy()
{
cout<<”\n\n\t derived
class…”;
cout<<”\n\tx=”<<x;
cout<<”\n\ty=”<<y;
}};
void main()
{
derived
obj; int
x,y;
clrscr();
cout<<”\n enter the value
of x: ”; cin>>x;
cout<<”\n enter the value
24
of y: ”; cin>>y;
obj.set_x(x);//inherits base class
obj.set_y(y);//acess member of derived
class obj.show_x();//inherits base class
obj.show_xy();//acess member of
derived class getch();
}

Output:
enter the value of
x 10 enter the
value of y 20

base
class….
x=10

derived
class…..
x=10
y=20

25
Result:
Thus the C++ program for inheritance was created, executed and output was
verified successfully.

26
[Link]
Build a C++ program to perform list operations
using linked list.

Aim:

To write a C++ program to implement a linked list and do all operations on it.

Algorithm:

1. Start the process.


2. Initialize and declare variables.
3. Enter the choice.

4. If choice is INSERT
then Enter the element to
be inserted.
i. Get a new node and set DATA[NEWNODE] = ITEM.
ii. Find the node after which the new node is to be inserted.
iii. Adjust the link fields.
iv. Print the linked list after
insertion.

[Link] choice is DELETE then


i. Enter the element to be deleted.
ii. Find the node containing the element (LOC) and its
preceding node (PAR). [Link] ITEM = DATA[LOC] and
delete the node LOC.
iv. Adjust the link fields so that PAR points to the next element. ie
LINK[PAR] = LINK [ LOC].
v. Print the linked list after deletion.
[Link] the process.
27
Program:
#include<iostream.
h>
#include<conio.h
>
#include<lib.h>
#define TRUE 1
#define
FALSE 0 class
sll
{
private:
struct node
{
int data;
struct node *next;
}*head;
public:
sll();
void
create();
void
display();
void search(int
key); void
insert_head();
void
insert_after();
void
insert_last();
void dele();
~sll();
};
sll::sll()
{
head=NULL;
}
28
sll::~sll()
{
node
*temp,*temp1;
temp=head-
>next; delete
head;
while(temp!=NU
LL)
{
temp1=temp-
>next; delete
temp;
temp=temp1;
}}
void sll::create()
{
node
*temp,*New; int
val,flag;

29
char
ans='y';
flag=TRU
E; do
{
cout<<"\n\nEnter the data:";
cin>>val;
New=new node;
if(New==NULL)
cout<<"unable to allocate
memory\n"; New->data=val;
New->next=NULL;
if(flag==TRUE)//executed only for the first time
{
head=New;
temp=head;
flag=FALSE;
}else
{
temp->next=New;
temp=New;
}
cout<<"\n do you want to enter more
elements?(y/n)"; ans=getch();
}
while(ans=='y'||ans=='Y');
cout<<"\n the singly linked list is created\n"; getch();
}
void sll::display()
{
node *temp;
temp=head;
if(temp==NULL)
{
cout<<"\n the list is
empty\n"; getch();
clrscr();
30
return;
}while(temp!=NULL)
{
cout<<temp-
>data<<" ";
temp=temp->next;
}getch();
}
void sll::search(int key)
{
node *temp; int
found; temp=head;
if(temp==NULL)
{
cout<<"linked list is
empty\n"; getch();
clrscr();
}
found=FALSE;
while(temp!=NULL&&found==FA
LSE)
{
if(temp-
>data!=key)
temp=temp-
>next; else
found=TRUE;
}if(found==TRUE)
{
cout<<"\n the element is present in the
list\n"; getch();
}else
{
cout<<"\nThe element is not present in the
list\n"; getch();
}}void sll::dele()
{

31
node
*temp,*prev; int
key;
temp=head;
cout<<"\n Enter the data of the node you want to
delete: "; cin>>key;
while(temp!=NULL)
{
if (temp->data==key)//traverse till required node to delete
break; //is found prev=temp;
temp=temp->next;
}
if(temp==NULL)
cout<<"\n node not
found"; else
{
if(temp==head)//first node
head=temp-
>next; else
prev->next=temp->next; //intermediate or end
node delete temp;
cout<<"\n the element is deleted\n";
}
getch();
}void sll::insert_last()
{
node *New,*temp;
cout<<"\n Enter the element which you want
to insert: "; cin>>New->data;
if(head==NULL)
head=New;
else
{
temp=head;
while(temp-
>next!=NULL)
temp=temp->next;
32
temp-
>next=New;
New-
>next=NULL;
}}void sll::insert_after()
{
int key;
node *temp,*New;
New=new node;
cout<<"\n Enter the element which you want
to insert: "; cin>>New->data;
if(head==NULL)
{
head=New;
}else
{
cout<<"\n Enter the element after which you want to insert the
node: "; cin>>key;
temp=hea
d; do
{
if(temp->data==key)
{
New->next=temp-
>next; temp-
>next=New; break;
}
else temp=temp->next;
}
while(temp!=NULL);
}}void sll::insert_head()
{
node *New,*temp;
New=new node;
cout<<"\n Enter the element which you want
to insert: "; cin>>New->data;

33
if(head==NULL)
head=New;
else
{
temp=head;
New->next=temp;
head=New;
}}void main()
{
sll s;
int choice,val,
ch1; char
ans='y';
clrscr();
cout<<"\n\n\tProgram to perform various operations on linked
list"; cout<<"\[Link]";
cout<<"\[Link]
y";
cout<<"\[Link]
h";
cout<<"\[Link] an element in
a list"; cout<<"\[Link] an
element from list";
cout<<"\[Link]";
do
{
cout<<"\n\nEnter your
choice(1-6): "; cin>>choice;
switch(choice)
{
case 1:
[Link]();
break;
case 2:
[Link]();
break;
case 3:
34
cout<<"enter the element you want to
search"; cin>>val;
[Link](val);
break;
case 4:
clrscr();
cout<<"\n the list
is:\n"; [Link]();
cout<<"\n menu";
cout<<"\[Link] at
beginning ";
cout<<"\[Link] after";
cout<<"\[Link] at end";
cout<<"\n enter your
choice"; cin>>ch1;
switch(ch1)
{
case 1:
s.insert_head(
); break;
case 2:
s.insert_after();
break;
case 3:
s.insert_last();
break;
default:
cout<<"\n invalid
choice"; break;
}
case 5:
[Link]();
break;
case 6:
exit(0);
default:
cout<<"\n invalid choice";
35
}
cout<<"\nDo you want to
continue? "; cin>>ans;
}
while(ans=='y'||ans=='
Y'); return;
}

36
Output:
Program to perform various operations on linked list
1. Create
2. Display
3. Search
4. Insert an element in a list
5. Delete an element from list
6. Quit

Enter your choice(1-6): 1 Enter the data:1

Do you want to enter more


elements?(y/n) Enter the data:2
Do you want to enter more
elements?(y/n) Enter the data:3
Do you want to enter more
elements?(y/n) the singly linked
list is created
Do you want to
continue? Y Enter
your choice(1-6): 2
123
Do you want to
continue? Y Enter
your choice(1-6): 3
enter the element you want to
search2 the element is present
in the list
Do you want to
continue? Y Enter your
choice(1-6): 4 the list
is:1 2 3

menu
1. insert at
beginning
[Link] after
[Link] at end
enter your choice1

37
Enter the element which you want to
insert: 4 Do you want to continue? y
Enter your choice(1-6): 5
Enter the data of the node you want to
delete: 2 the element is deleted
Do you want to
continue? Y Enter
your choice(1-6): 5
Enter the data of the node you want to
delete: 12 node not found
Do you want to continue? y Enter your choice(1-6): 6

Result:
Thus the C++ program for linked list implementation of list ADT was created,
executed and output W was verified successfully

38
[Link]
Construct a C++ program to perform stack operation
using array

Aim:
To write a C++ program for stack using array implementation.

Algorithm:

1. Define a array which stores stack


elements.. [Link] operations on the
stack are
a) PUSH data into the stack
b) POP data out of stack
3. PUSH DATA INTO STACK
[Link] the data to be inserted into stack.
b .If TOP is NULL the input data is the first node in stack. the link of the
node is
NULL.
c. If TOP is NOT NULL the link of TOP points to the new node.

4. POP DATA FROM STACK


a. If TOP is NULL the stack is empty
b. If TOP is NOT NULL the link of TOP is the
current TOP. The pervious TOP is popped
from stack.
5. The stack represented by linked list is traversed to display its content.

39
Program:
#include<iostream.
h>
#include<conio.h
>
#include<stdlib.h
> class stack
{
int
stk[5];
int top;

40
public:
stack()
{
top=-1;
}
void push(int x)
{
if(top > 4)
{
cout <<"stack over
flow"; return;
}
stk[++top]=x;
cout <<"inserted" <<x;
}
void pop()
{
if(top <0)
{
cout <<"stack under
flow"; return;
}
cout <<"deleted" <<stk[top--];
}
void display()
{
if(top<0)
{
cout <<" stack

41
empty"; return;
}
for(int
i=top;i>=0;i--)
cout <<stk[i] <<"
";

}
};
main()
{
int ch;
stack
st;
clrscr()
;
cout <<"\[Link] \[Link] \[Link] \[Link]"; while(1)
{
cout<<"\nEnter ur
choice"; cin >> ch;
switch(ch)
{
case 1: cout <<"enter the
element"; cin >> ch;
[Link](ch);
break;
case 2:
[Link]();
break;

42
case 3:
[Link]();
break;
case 4: exit(0);
}
}
return (0);
}

43
Output:
1. push
[Link]
[Link]
ay
[Link]

Enter ur choice: 1 enter the


element: 3 inserted3
Enter ur choice: 1 enter the
element: 5 inserted: 5

Enter ur choice: 1 enter the


element: 7 inserted: 7
Enter ur choice: 3 7 5 3

Enter ur
choice: 2
Deleted: 7

Enter ur choice:

3 5 3 Enter ur

choice:4

Result:
Thus the C++ program for array implementation of stack ADT was created,
executed and output was verified successfully.
44
[Link] Develop a C++ application to perform insertion sort, quick sort and
merge sort.

Aim:
To write a c++ program to perform quick sort.
Algorithm:
1. Get the value of how many no. to
be sorted. [Link] the number of
elements from the user.
3. Merge sort algorithm works The list to be sorted is divided into two arrays
of equal length by dividing the list on the middle element. If the number of
elements in the list is either 0 or 1, then the list is considered sorted.
4. Each sublist is sorted individually by using merge sort recursively.
5. The sorted sublists are then combined or merged together to form a complete
sorted list.
6. Display the sorted value.

Program:
#include
<iostream.h>
#include<conio.h
>
void merge(int *,int, int , int );
void merge_sort(int *arr, int low, int high)
{
int mid;
if (low < high)
{
//divide the array at mid and sort independently using

45
merge sort mid=(low+high)/2;
merge_sort(arr,low,mid);
merge_sort(arr,mid+1,high);
//merge or conquer sorted
arrays
merge(arr,low,high,mid);
}
}
// Merge sort
void merge(int *arr, 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 (arr[i] < arr[j])
{
c[k] =
arr[i];
k++;
i++;
}
else {
c[k] =
arr[j];
k++;
46
j++;
}
}
while (i <=
mid) { c[k] =
arr[i]; k++;
i++;
}
while (j <=
high) { c[k] =
arr[j]; k++;
j++;
}
for (i = low; i < k;
i++) { arr[i] = c[i];

}
}
// read input array and call
mergesort int main()
{
int myarray[30], num;
cout<<"Enter number of elements to be
sorted:"; cin>>num;
cout<<"Enter "<<num<<" elements to be
sorted:"; for (int i = 0; i < num; i++) {
cin>>myarray[i];
}
merge_sort(myarray, 0, num-

47
1); cout<<"Sorted array\n";
for (int i = 0; i < num; i++)
{
cout<<myarray[i]<<"\t";
}
}

Output:

Enter the number of elements to be sorted:10

Enter 10 elements to be sorted: 101 10 2 43 12 54 34 64

89 76 Sorted array

2 10 12 34 43 54 64 76 89 101

Result:
Thus the C++ program for merge sort was created, executed and output was
verified successfully

48
[Link]
Write a C++ programs to implement recursive and non
recursive
i) Linear search ii) Binary search

Aim:
To write a c++ program to perform quick sort.

Algorithm:
1. Read the search element from the user
2. Find the middle element in the sorted list
3. Compare, the search element with the middle element in the sorted list.
4. If both are matching, then display "Given element found!!!" and terminate the function
5. If both are not matching, then check whether the search element is smaller or
larger than middle element.
6. If the search element is smaller than middle element, then repeat steps 2, 3, 4
and 5 for the left sublist of the middle element.
7. If the search element is larger than middle element, then repeat steps 2, 3, 4
and 5 for the right sublist of the middle element.
8. Repeat the same process until we find the search element in the list or until sublist
contains only one element.
9. If that element also doesn't match with the search element, then display " No
Match Found " and terminate the function.

Program:
#include <
iostream.h>
#include <
conio.h>
int binarySearch(int arr[], int left, int right,

49
int x) { while (left <= right) {

int mid = left + (right -

left) / 2; if (arr[mid] == x)

return mid;
} else if (arr[mid] <

x) { left = mid + 1;

}
else {

right = mid - 1;

return -1;

int main()
{

int

myarr[10];

int num;

int output;

cout << "Please enter 10 elements ASCENDING

50
order" << endl; for (int i = 0; i < 10; i++) {

cin >> myarr[i];

cout << "Please enter an element to search"

<< endl; cin >> num;

output = binarySearch(myarr, 0,

9, num); if (output == -1) {

cout << "No Match Found" << endl;


} else
{

cout << "Match found at position: " << output << endl;

return 0;

51
Output:

Please enter 10 elements ASCENDING order


1 5 8 9 14 25 68 59 74 81
Please enter an element to
search 14 Match found at
position: 5

Result:
Thus the C++ program for binary search was created, executed and output
was verified successfully

52

You might also like