0% found this document useful (0 votes)
21 views95 pages

Ec6301 Dec

The document discusses object oriented programming concepts. It defines object oriented programming as a method of implementation where programs are organized as cooperative collections of objects. Each object represents an instance of a class, and classes are arranged in a hierarchy connected through inheritance. The basic concepts of OOP include objects, classes, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. Encapsulation wraps data and functions into a single unit to protect data from external interference. Data abstraction represents essential features without background details. Inheritance allows code reuse through derived classes. Polymorphism allows single names to have different implementations depending on the data type. Dynamic binding determines code execution at runtime based on the object.

Uploaded by

sdarunprasad
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)
21 views95 pages

Ec6301 Dec

The document discusses object oriented programming concepts. It defines object oriented programming as a method of implementation where programs are organized as cooperative collections of objects. Each object represents an instance of a class, and classes are arranged in a hierarchy connected through inheritance. The basic concepts of OOP include objects, classes, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. Encapsulation wraps data and functions into a single unit to protect data from external interference. Data abstraction represents essential features without background details. Inheritance allows code reuse through derived classes. Polymorphism allows single names to have different implementations depending on the data type. Dynamic binding determines code execution at runtime based on the object.

Uploaded by

sdarunprasad
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
You are on page 1/ 95

Downloaded From : www.EasyEngineering.

net

ww
w.E
a syE
ngi
nee
rin
g.n
et

**Note: Other Websites/Blogs Owners Please do not Copy (or) Republish


this Materials, Students & Graduates if You Find the Same Materials with
EasyEngineering.net Watermarks or Logo, Kindly report us to
[email protected]

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

DHANALAKSHMI COLLEGE OF ENGINEERING


DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING
EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
YEAR / SEM: II / 03 UNIT I
DATA ABSTRACTION AND OVERLOADING
Part A

1. What are the characteristics of procedure oriented programming?


The characteristics of procedure oriented programming are:
1) Emphasis on doing things.
2) Large programs are divided into smaller programs known as functions

ww 3) Most of the functions share global data


4) Data can move openly around the system from function to function

w.E
2. What are the features of object oriented programming?
The features of object oriented programming are:

asy
1) Programs are divided into objects.
2) Data is hidden.

En
3) Objects communicate with each other, by sending messages and receiving responses.
4) It follows bottom up approach

gin
3. Distinguish between procedure oriented programming and object oriented programming.

Procedure oriented programming ee rin


Object oriented programming

Emphasis is on algorithm g.n


Emphasis is on data rather than procedure

Large programs are divided into smaller


programs called functions
et
Programs are divided into objects

Function that operate on the data of an object


Functions share global data
are tied together

Data move openly around the system from Data is hidden and cannot be accessed by
function to function external functions

Top down approach Bottom up approach

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

4. Define – Object Oriented Programming


Object Oriented Programming is defined as a method of implementation in which
programs are organized as co−operative collection of objects, each of which represents an instance
of some class and whose classes are all members of a hierarchy of classes united through the class.

5. List out the basic concepts of object oriented programming.


The basic concepts of object oriented programming are:
1) Objects
2) Classes
3) Data abstraction and encapsulation
4) Inheritance

ww 5) Polymorphism
6) Dynamic binding

w.E 7) Message passing

6. Define – Encapsulation and Data Hiding

asy
Encapsulation is defined as wrapping up of data and functions into a single unit so that the
data is kept safe from external interference and misuse.

En
Data hiding is defined as the isolation of data from direct access by the program which is
called data hiding or information hiding.

7. Define – Data Abstraction gin


the background details. ee
Data Abstraction is defined as the act of representing essential features without including

rin
It gives a clear separation between properties of data type and the associated

g.n
implementation details. There are two types that are "function abstraction" and "data abstraction".
Function that can be used without knowing how it is implemented is function abstraction. Data
abstraction is using data without knowing how the data is stored.

8. Define – Inheritance
et
Inheritance is defined as the process by which objects of one class acquire the properties
of the objects of another class. The new derived class inherits the members of the base class and also
adds its own.
Inheritance provides the concept of reusability in C++.

9. Define – Polymorphism
Polymorphism is defined as single name/operator to be associated with different
operations depending on the type of data passed to it. An operation may exhibit different
behaviors in different instances.

10. List out the two types of polymorphism.


The two types of polymorphism are:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

1) Compile time polymorphism


2) Run time polymorphism

11. Define – Dynamic Binding


Dynamic binding is defined as the code associated with the given procedure call is not
known until the time of call at runtime.
In OOPs, Dynamic Binding refers to linking a procedure call to the code that will be
executed only at run time. The code associated with the procedure is not known until the program is
executed, which is also known as late binding.

12. Define – Message Passing


Message passing is defined as the process of invoking an operation on an object. In
response to a message, the corresponding function is executed in the object.

ww
13. List out the benefits of object oriented programming.

w.E
The benefits of object oriented programming are:
1) The principle of data hiding helps to build secure programs.
2) Through inheritance, redundant code is eliminated.

asy
3) Software complexity can be easily managed.

En
14. Distinguish between data encapsulation and data abstraction.
[N/J–10]
Data Encapsulation
gin
The wrapping up of data and functions
Data abstraction

into a single unit is known as


encapsulation.
The data is kept safe from external
eeIt refers to the act of representing essential features
without including the background details.

rin
interference and misuse.
Data is unsafe.
g.n
15. Write the need of object oriented paradigm.
The needs of object oriented programming are:
a) Real time system
et
b) Simulation and modeling
c) AI and expert system
d) Neural network programming
e) CAD/CAM systems

16. Define – Inline Function [M/J–13]


Inline function is defined as the function that is expanded in line when it is invoked. Compiler
replaces the function call with the corresponding function code.
Inline function header
{
function body

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

17. Define – Function Prototyping


A function prototype or function interface in C++ is defined as a declaration of a
function that omits the function body but does specify the function's return type, name and argument
types. A function prototype merely specifies its interface. Function prototype is the declaration
statement in the calling program.
In a prototype, argument names are optional (and have function prototype scope, meaning
they go out of scope at the end of the prototype), however, the type is necessary along with all
modifiers (e.g. if it is a pointer or a const argument).

18. What is meant by call by reference?


Call by reference means passing the address of a variable where the actual value is stored.

ww
The called function uses the value stored in the passed address.
In the call by reference method, instead of passing values to the function being called,

w.E
references/pointers to the original variables are passed. The call by reference method of passing
arguments to a function copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This means that

asy
changes made to the parameter affect the passed argument.

En
19. When inline expansion doesn’t work in C++?
Inline condition will not work when it is defined in long term.

20. Why are default arguments used? gin


ee
Default arguments assign the default value to the parameter, which does not have

rin
matching argument in the function call. Default value is specified when the function is declared.
C++ allow to specify default arguments that always have a value, even if one is not

g.n
specified when calling the function. For example, in the following function declaration:
int my_func(int a, int b, int c=12);

21. Define – Class


et [M/J–13]
A class is the collection of related data and function under a single name. A C++ program
can have any number of classes. When related data and functions are kept under a class, it helps
to visualize the complex problem efficiently and effectively.

The mechanism that allows combining data and the function in a single unit is called a class. Once a
class is defined, we can declare variables of that type. A class variable is called object or instance. In
other words, a class would be the data type, and an object would be the variable.
Classes are defined using a keyword class with the following syntax:
Class class_name
{
access_specifier_1:
member1;

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

access_specifier_2;
member2’

} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of names
for objects of this class. The body of the declaration can contain members, which can either be data
or function declarations, and optionally access specifiers.

22. Write the member declaration of a class static. [N/J–09]


A static member function can only access static data member, other static member
functions and any other functions from outside the class. Static member functions have a class
scope and they do not have access to this pointer of the class. It uses a static member function to

ww
determine whether some objects of the class have been created or not.

w.E
23. What are the effects of visibility labels such as private, protected, and public have on the
members of a class?
The effects of private, protected, public are:
[N/J–10]

asy
a) Private - it is only accessible to local members of the class
b) Protected - it is accessible only to members of the class

En
c) Public - it can be accessed by any class members

24. How is the class declared in C++?


gin [A/M–10]
Class is defined as to bind data and its associated functions together that is declared as:
class A
{
public:
ee rin
};
void function();
g.n
{
int main()

A myObject;
et
myObject.function();
}
void A::function()
{
cout<<"Hello World!";
}

25. What is scope resolution operator? [A/M–10]


Scope resolution operator is used to unhide the global variable that might have got
hidden by the local variables. Hence in order to access the hidden global variable one needs to
prefix the variable name with the scope resolution operator (::).

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Ex: int i = 10; int main ()


{
int i = 20;
cout << i; // this prints the value 20
cout << ::i; // in order to use the global i one needs to prefix it with the scope resolution
operator.
}
The second use of the operator is to access the members declared in class scope. Whenever a
scope resolution operator is used, the name of the member that follows the operator is looked up in
the scope of the class with the name that appears before the operator.

26. Define – Object [N/J–12]

ww Object is defined as an instantiation of a class. In terms of variables, a class would be the


type, and an object would be the variable.
When class is defined, only specification for the object is defined. Object has same

w.E
relationship to class as variable has with the data type. Objects can be defined in similar way as
structure is defined.

asy
Syntax to define object in C++:
class_name variable name;

En
For the above defined class temp, objects for that class can be defined as:
temp obj1,obj2;

gin
Here, two objects(obj1 and obj2) of temp class are defined.

27. What is meant by reference variable?


ee rin
A reference variable is an alias, that is, another name for an already existing variable.
Once a reference is initialized with a variable, either the variable name or the reference name may
be used to refer to the variable
Creating References in C++: g.n
et
Think of a variable name as a label attached to the variable's location in memory. We can
then think of a reference as a second label attached to that memory location. Therefore, we can
access the contents of the variable through either the original variable name or the reference. For
example, suppose we have the following example:
int i = 17;
We can declare reference variables for i as follows.
int& r = i;
Read the & in these declarations as reference. Thus, read the first declaration as "r is an integer
reference initialized to i".

28. How is variable initialized in C++?


The variables have an undetermined value until they are assigned a value for the first time. But it
is possible for a variable to have a specific value from the moment it is declared. This is called
the initialization of the variable.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

type identifier = initial_value;


Example: int x = 0;

29. Define – Proxy Class


A proxy is a class that provides a modified interface to another class. It is a class that acts on
behalf of another class. There are many uses for proxy classes, but generally they are used to
simplify a complex object's interface, by hiding details that are of no relevance within the object's
current context.

30. Define – Container Class


A container class is a class that is used to hold objects in memory or external storage. A
container class acts as a generic holder. A container class has a predefined behavior and a well-

ww
known interface. A container class is a supporting class whose purpose is to hide the topology used
for maintaining the list of objects in memory. When a container class contains a group of mixed

w.E
objects, the container is called a heterogeneous container; when the container is holding a group of
objects that are all the same, the container is called a homogeneous container.

31. What is a constructor?


asy [N/J–12]
The constructor is a specialized method that is contained in a class. The constructor will be

En
triggered automatically when an object is created. Purpose of the Constructors is to initialize an
object of a class. The constructor’s name is identical to the Class name. The constructors can take

gin
parameters but constructors have no return type.
A class can include a special function called its constructor, which is automatically called

ee
whenever a new object of this class is created, allowing the class to initialize member variables or

rin
allocate storage. This constructor function is declared like a regular member function, but with a
name that matches the class name and without any return type; not even void.

32. What is a destructor? g.n


et
When an object is no longer needed it can be destroyed. A class has another special member
function called destructor, which is invoked when an object is destroyed. For objects which are local
non-static variables, the destructor is called when the function in which the object defined is about
to terminate.

33. Why is it necessary to overload an operator? [N/J–09]


In case to design our own class and want the user (programmer) to have a transparent
way to work with your class then operator overloading is a good thing. Using this overloading we
can easily access the objects to perform any operations.

34. What are the advantages of operator overloading? [N/J–10]


Operator overloading is the property of Object oriented programming which gives an extra
ability to an operator to act on a User-defined operand (Objects).
Advantages:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

 It will act differently depending on the operands provided that is called extensibility.
 It is not limited to work only with primitive data type.
 By using this overloading, we can easily access the objects to perform any operations.
 It makes code much more readable.

35. What are the special operators that cannot be overloaded? [N/J–12]
There are 5 operators which cannot be overloaded. They are:
a) .* - class member access operator
b) :: - scope resolution operator
c) . - dot operator
d) ?:: - conditional operator
e) Sizeof() - operator

ww PART - B

w.E UNIT I
DATA ABSTRACTION AND OVERLOADING
36. Concepts of object oriented programming:

asy
OOP is defined as a method of implementation in which programs are organized as
cooperative collection of objects, each of which represents an instance of some class and whose

En
classes are all members of a hierarchy of classes united through the class.

gin
The basic concepts of object oriented programming are:
8) Objects
9) Classes

11) Inheritance
12) Polymorphism
ee
10) Data abstraction and encapsulation

rin
13) Dynamic binding
14) Message passing g.n
a) Object:
et
Object is defined as an instantiation of a class. In terms of variables, a class would be the
type, and an object would be the variable. These are the basic run time entities in an object
oriented program.
When class is defined, only specification for the object is defined. Object has same
relationship to class as variable has with the data type. Objects can be defined in similarly way
as structure is defined.
Syntax to define object in C++:
class_name variable name;
For the above defined class temp, objects for that class can be defined as:
temp obj1,obj2;
Here, two objects(obj1 and obj2) of temp class are defined.

b) Class:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

A class is the collection of related data and function under a single name. The mechanism that
allows combining data and the function in a single unit is called a class. Once a class is defined,
we can declare variables of that type. Classes are defined using a keyword class with the following
syntax: Class class_name
{
access_specifier_1:
member1;
access_specifier_2;
member2;

} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of

wwnames for objects of this class. The body of the declaration can contain members, which can
either be data or function declarations, and optionally access specifiers.

w.E
c) Data abstraction and Encapsulation:

asy
Data abstraction: It refers to the act of representing essential features without including the
background details.

En
Encapsulation is the method of combining the data and functions inside a class. This hides
the data from being accessed from outside a class directly, only through the functions inside the

gin
class is able to access the information. This is also known as "Data Abstraction", as it gives a
clear separation between properties of data type and the associated implementation details.

ee
There are two types, they are "function abstraction" and "data abstraction". Functions that

rin
can be used without knowing how its implemented is function abstraction. Data abstraction is
using data without knowing how the data is stored.
#include <iostream.h>
class Add g.n
{
private:
int x,y,r;
et
public:
int Addition(int x, int y)
{ r= x+y;
return r; }
void show( )
{ cout << "The sum is::" << r << "\n";}
}s;
void main()
{
Add s;

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

s.Addition(10, 4);
s.show();
}
In the above encapsulation example the integer values "x,y,r" of the class "Add" can be
accessed only through the function "Addition". These integer values are encapsulated inside the
class "Add".
d) Inheritance:
It is the process by which the objects of one class acquire the properties of objects of another
class. The new derived class inherits the members of the base class and also adds its own. Base
class is defined as the parent class that cannot not be inherit from any other class. Derived class
is defined as a new class which inherits from the base class.

ww The types of inheritance are:


1) Single inheritance

w.E 2) Multiple inheritance


3) Hierarchical inheritance

asy
4) Multilevel inheritance
5) Hybrid inheritance

En
The advantages of inheritance are:
1) Inheritance provides the concept of reusability in C++.

gin
2) Classes can be reused using inheritance.
3) Classes can access the attributes of base classes.
e) Polymorphism:
ee rin
It allows a single name/operator to be associated with different operations depending
on the type of data passed to it. An operation may exhibit different behaviors in different
instances.
g.n
Polymorphism means “having many forms”. It allows different
objects to respond to the same message in different ways, the response specific to the type of the

a) Operator overloading
b) Function overloading
et
object. The concept of polymorphism is implemented using overloaded functions and operators.

a) Operator overloading:
The process of making an operator to exhibit different behaviors in different instances is
known as Operator overloading.
b) Function overloading:
To perform different types of tasks or functions using a single function name is known
as Function overloading.
f) Dynamic Binding:
Dynamic binding is defined as the code associated with the given procedure call is not
known until the time of call at runtime.
g) Message passing:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Message passing is defined as the process of invoking an operation on an object. In


response to a message, the corresponding function is executed in the object.
Comparison of structured programming and object oriented programming:

Structured programming Object oriented programming


Emphasis is on algorithm. Emphasis is on data rather than procedure.
Large programs are divided into smaller
Programs are divided into objects.
programs called functions.
Functions that operate on the data of an object
Functions share global data.
are tied together.
Data move openly around the system from Data is hidden and cannot be accessed by
function to function external functions.
Top-down approach. Bottom-up approach.

ww
37. Structure of C++ program:
It is of three types:

w.E 1. Sequence structure


2. Selection structure

asy
3. Loop or iteration or repetition structure
C++ supports all the control structures of C. The control structures if, and switch are selection
structures. The control structures do…while, while, and for are called loop structure. The if

En
keyword is used to execute a statement or block only if a condition is fulfilled.
Its form is:
gin
if (condition) statement

ee
where condition is the expression that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the program continues right after this
conditional structure.
rin
g.n
The format of while loop is:
while (expression)
statement

et
and its functionality is simply to repeat statement while the condition set in expression is true.
The format of for loop is:
for (initialization; condition; increase)
statement;
and its main function is to repeat statement while condition remains true, like the while loop. But in
addition, the for loop provides specific locations to contain an initialization statement and an
increase statement. So this loop is specially designed to perform a repetitive action with a counter
which is initialized and increased on each iteration.
It works in the following way:
 Initialization is executed. Generally it is an initial value setting for a counter variable. This
is executed only once.
 Condition is checked. If it is true the loop continues, otherwise the loop and statement is
skipped (not executed).
 Statement is executed. It can be either a single statement or a block enclosed in braces { }.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

 Finally, whatever is specified in the increase field is executed and the loop gets back to
step 2.
The syntax of the switch statement is a bit peculiar. Its objective is to check several
possible constant values for an expression. Something similar to what we did at the beginning of
this section with the concatenation of several if and else if instructions. Its form is the following:
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;

ww break;
.
.

w.E .
default:

asy
default group of statements
}
It works in the following way:
En
switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group

gin
of statements 1 until it finds the break statement. When it finds this break statement the program
jumps to the end of the switch selective structure. If expression was not equal to constant1 it will be

ee
checked against constant2. If it is equal to this, it will execute group of statements 2 until a break

rin
keyword is found, and then will jump to the end of the switch selective structure. Finally, if the
value of expression did not match any of the previously specified constants (you can include as

g.n
many case labels as values you want to check), the program will execute the statements included
after the default: label, if it exists (since it is optional).

38. Function Overloading: et


Function overloading is defined as that we can use the same function name to create functions
that perform a variety of different tasks.
Ex:
int add(int a, int b);
int add(int a, int b, int c);
int add(int a, int b, int c, int d);
A function is overloaded when same name is given to different function. However, the two
functions with the same name will differ at least in one of the following.
a) The number of parameters
b) The data type of parameters
c) The order of appearance
While overloading a function, the return type of the functions needs to be the same.In general

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

functions are overloaded when:


a) Functions differ in function signature.
b) Return type of the functions is the same.
Here s a basic example of function overloading:
#include<iostream>
using namespace std;
class arith { public: void
calc(int num1)
{
cout<<”Square of a given number: ― “<<num1*num1 <<endl;
}
void calc(int num1, int num2 )

ww {
cout<<”Product of two whole numbers: ― “<<num1*num2 <<endl;
}

w.E };

asy
int main() //begin of main function
{
arith a;
En
a.calc(5); a.calc(6,7);
}
Example of function overloading:gin
ee
First the overloaded function in this example is calc. If you have noticed we have in our
‘arith’ class two functions with the name calc. The fist one takes one integer number as a

rin
parameter and prints the square of the number. The second calc function takes two integer

g.n
numbers as parameters, multiplies the numbers and prints the product. This is all we need for
making a successful overloading of a function.
 we have two functions with the same name : calc
 we have different signatures : (int) , (int, int)
 return type is the same : void
et
39. Friend function:
A friend function is used for accessing the non-public members of a class. A class can allow non
member functions and other classes to access its own private data, by making them friends. Thus, a
friend function is an ordinary function or a member of another class.
A friend function of a class is defined outside that class' scope but it has the right to access all
private and protected members of the class. Even though the prototypes for friend functions appear
in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class template, in
which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class definition

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

with keyword friend as follows:


class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
Example program: To find the mean value of a given number using friend function.
#include<iostream.h>
#include<conio.h>
class base

ww {
int val1,val2;
public:

w.E void get()


{

asy
cout<<"Enter two values:";
cin>>val1>>val2;
}
En
friend float mean(base ob);
};
float mean(base ob) gin
{

}
ee
return float(ob.val1+ob.val2)/2;

rin
void main()
{
g.n
clrscr();
base obj;
obj.get();
et
cout<<"\n Mean value is : "<<mean(obj);
getch();
}
Merits:
 We can able to access the other class members in our class if, we use friend keyword.
 We can access the members without inheriting the class.
Demerits:
 Maximum size of the memory will occupied by objects according to the size of friend
Members.
 We can’t do any run time polymorphism concepts in those members.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

40. Constructor and Destructor:


Constructor:
A constructor is a special member function used to allocate the required resources such as
memory and initialize the object of its class. A constructor is distinct from other member
functions of the class, and it has the same name as its class. It is executed automatically when a
class is instantiated (object is created).
The C++ run-time system makes sure that the constructor of class is the first number
function to be executed automatically when an object of the class is created. In other words, the
constructer is executed every time an object of that class is defined. Normally constructors are
used for initializing the class data members. The syntax for defining a constructor with its
prototype within the class body and the actual definition outside it, is given below:
Syntax for constructor:

ww Class ClassName
public:
//public members
must be public

w.E };
ClassName :: ClassName() Constructor definition
{
asy
// Constructor body definition
}
En
//test1.cpp: a class test with a constructor function

gin
#include<iostream.h> class Test
{
public:
Test();
};
ee rin
Test::Test()
{
g.n
cout<<”constructor of class Test called”<<endl;
}
// test program: Test G;
et
Void func()
{
Test L;
Cout<<”here’s function func()”<<endl;
}
void main()
{
Test X;
Cout<<”main() function”<<endl; Func();
}
A constructor has the following characteristics:
a) It has the same as that of the class to which it belongs

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

b) It is executed automatically whenever the class instantiated


c) It does not have any return type
d) It is normally used to initialize the data members of a class
e) It is also used to allocate resources such as memory, to the dynamic data members of the
class
Destructor:
When an object is no longer needed it can be destroyed. A class has another special
member function called destructor, which is invoked when an object is destroyed. For objects
which are local non-static variables, the destructor is called when the function in which the
object is defined is about to terminate. For static or global variables, the destructor is called
before the program terminates.
Class ClassName

ww {
………….// private members
public: must be public

w.E //public members


~ClassName(); Destructor prototype
};
asy
ClassName :: ~ClassName() Destructor definition
{
En
// destructor body definition
}
gin
The purpose of constructor and destructor are:

ee
 The Constructor in a class is a special block of statements called when an object is

rin
created, either when it is declared or when it is dynamically constructed on the heap
through the keyword "new"

g.n
 In most languages, the constructor can be overloaded in that there can be more than
one constructor for a class, each having different parameters
Some languages take consideration of some special types of constructors:
a) default constructor - a constructor that can take no arguments et
b) copy constructor - a constructor that takes one argument of the type of the class
Constructors and Destructors are special member functions of classes that are used to
construct and destroy class objects. Construction may involve memory allocation and
initialization for objects. Destruction may involve cleanup and deallocation of memory for
objects.
Constructor function gets invoked when an object of a class is constructed (declared) and
destructor function gets invoked when the object is destructed (goes out of scope).
Like other member functions, constructors and destructors are declared within a class
declaration. They can be defined inline or external to the class declaration. Constructors can
have default arguments. Unlike other member functions, constructors can have member
initialization lists.
The following restrictions apply to constructors and destructors:
a) Constructors and destructors do not have return types nor can they return values

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

b) References and pointers cannot be used on constructors and destructors because


their addresses cannot be taken
c) Constructors cannot be declared with the keyword virtual
d) Constructors and destructors cannot be declared static, const, or volatile
e) Unions cannot contain class objects that have constructors or destructors
Use of Constructor and Destructor function of a class:
a) Constructor function is used to initialize member variables to pre-defined values as soon
as an object of a class is declared
b) Constructor function having parameters is used to initialize the data members to the
values passed values, upon declaration
c) Generally, the destructor function is needed only when constructor has allocated
dynamic memory

ww
Parameterized constructor:
Constructor is automatically called when object (instance of class) create. It is special member
function of the class, which constructor has arguments that is called Parameterized Constructor.

w.E
asy
The features of parameterized constructor are:
a) It has same name of class

En
b) It must be a public member
c) No return value

gin
d) Default constructors are called when constructors are not defined for the classes
Arguments can be passed to the constructor function when the objects are created. The

41. Operator Overloading:


ee
constructors that can take arguments are called as parameterized constructor.

rin
g.n
Operators can be overload using member functions or friend functions. Consider for example
the +operator. So far we used the +operator to add build-in data types that is to add any integer

et
or float etc. We can use the +operator to add two strings namely to concatenate 2 strings.
Overloading an operator does not change the basic template of an operator nor does it alter
its order of precedence. The main advantage of using overloading operators in a program is that
it is much easier to read and debug the program.
Operator overloading is a very important feature of Object Oriented Programming. It is
because by using this facility programmer would be able to create new definitions to existing
operators. In other words a single operator can perform several functions as desired by
programmers.
Operators can be broadly classified into:
a) Unary Operators
b) Binary Operators
Unary Operators:
As the name implies takes operate on only one operand. Some unary operators are namely,
++ - Increment operator

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

-- - Decrement Operator
! - Not operator
− - Unary minus.
Binary Operators:
The arithmetic operators, comparison operators, and arithmetic assignment operators come
under this category.
Operator Overloading –Unary operators:
Both the above classification of operators can be overloaded. Operator overloading helps
the programmer to define a new functionality for the existing operator. This is done by using the
keyword operator.
The general syntax for defining an operator overloading is as follows:
return_type classname :: operator operator

ww
symbol(argument)
{
…………..

w.E statements;
}

asy
Thus the above clearly specifies that operator overloading is defined as a member function
by making use of the keyword operator.
In the above:
En
a) return_type – is the data type returned by the function

gin
b) class name - is the name of the class
c) operator – is the keyword

new functionality ee
d) operator symbol – is the symbol of the operator which is being overloaded or defined for

rin
e) :: - is the scope resolution operator which is used to use the function definition outside
the class.
g.n
Operator overloading is done with the help if a special function. This function can be

return-type operator op symbol(argument list); et


member function or friend function. The general syntax of operator overloading is as follows.

where operator is the keyword and is preceded by the return-type of the function. Suppose we
want to concatenate 2 character strings using the +operator, we should use the following
declaration statement.
Char operator +(char * S2);

Overloading Unary Operator(-)


An unary operator can be overloaded using a member function or a friend function. When
we write a member function to overload unary operators we must pass no arguments to the
function. But if we write a friend function to overload the unary operator we must pass a single
argument to the function.
Consider the overloading of operator-in the following program that over loads the unary
operator to negate and object. The operator function defined outside the class negates the
individual data members of the class integer.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

#include<iostream.h>
#include<conio.h>
class integer
{
public :
void getdata(int a,int b,int c);
void disp(void);
voidoperator();
};
void integer::getdata(int a,int b,int c)
{
x=a;

ww y=b;
z=c;
}

w.E void integer::disp(void)


{
cout<<x<<”
cout<<y<<” asy ”;
”;
cout<<z<<” ”;
}
En
gin
void integer::operator – ()
{

}
x=-x; y=-y; z=-z;

void main()
ee rin
{
integer S;
g.n
S.getdata (11,-21,-31);
cout<<”S:” ;
S.disp ();
et
-S;
cout<<”S:” ;
S.disp ();
getch();
}
Note the function written to overload the operator is a member function. Hence no argument
is passed to the function. In the main() function, the statement –S invokes the operator function
which negatesindividual data elements of the object S.

Overloading Binary Operator (+)


Binary operators are operators which require two operands tp perform the operation when
they are overloaded by means of member function, the function takes one argument, whereas it

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

takes two arguments in case of friend function. This will be better understood by means of the
following program.
Program illustrates the +operator overloaded to find the sum of two objects. The following
creates two objects of class integer and overloads the +operator to add two object values.
#include<iostream.h>
#include<conio.h>
Class integer
{
private:
int val;
public:
integer(); integer (int one);

ww integer operator +(integer obj b);


void disp();
};

w.E integer :: integer()


{
val =0;
} asy
En
integer :: integer (int one)
{
val= one;
} gin
{
integer objsum;
ee
integer integer :: operator +(integer obj b)

rin
intesum. Val=val +obj b.val;
return (objsum);
g.n
void integer :: disp()
{
cout<<”value =”<<val<<endl;
et
}
void main()
{
integer obj1(11);
integer obj2(22);
integer objsum;
objsum = obj1 + obj2;
obj1. disp();
obj2. disp();
objsum. disp();
getch();
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Note that the operator overloading function is invoked by S3 =S1 + S2. We have passed only
one argument to the function. The left hand object S1 invokes the function of S2 is actually the
argument passed to function.
C++ program to illustrate operator overloading through friend functions:
#include<iostream.h>
#include<conio.h>
#include<s
tdlib.h>
class stud
{
int
rno;

ww char
*na
me;

w.E int;
publ
ic:
asy
friend istream &operator>>(istream
&,stud &);
Enfriend
operator<<(ostream &,stud &);
void

};
gin
istream &operator>>(istream &tin,stud &s)
{
ee
cout<<"\n Enter the no"; tin>>s.rno;
cout<<"\n Enter
rin
the
tin>>s.name;
name";
g.n
cout<<"\n
Enter";
tin>>s.marks;
et
return tin;
}
void operator<<(ostream &tout,stud &s)
{
tout<<”\n”<<s.rno;
tout<<”\n”<<s.name;
tout<<”\n”<<s.marks;
}
void main()
{
clrscr();
cout<<"\t\tBinaryOperator Overloading Using FriendFunction"; stud s;

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

for(int i=0;i<3;i++)
{
cin>>s;
}
for( i=0;i<3;i++)
{
cout<<s;
}
getch();
}
C++ program to overload ‘= =’ to distinguish between two strings:
A string object holds and manipulates an arbitrary sequence of bytes, typically representing

ww
characters.
#include<conio.h>
#include<string.h>

w.E num boolean{F,T};


const int s=50;
class string
{ asy
char str[s];
public:
En
string()
{ gin
strcpy(str," ");
}
void read()
ee rin
{
cin>>str;
g.n
}
void show()
{
et
cout<<str;
}
boolean operator <(string s)
{
if (strcmp(str,s.str)<0)
return T;
else
return F;
}
boolean operator >(string s)
{
if (strcmp(str,s.str)>0)

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

return T;
else
return F;
}
boolean operator ==(char *s)
{
if(strcmp(str,s)=)
return T;
else
return F;
}
};

ww void main()
{
clrscr();

w.E string
str1,str2;
while(T)
{ asy
En
cout<<"\n enter string1<'end' to stop>:";
str1.read();
if(str1=="end")
break; gin
cout<<"\n enter string2:";
ee
str2.read(); cout<<"comparison status:";
str1.show();
rin
if(str1<str2)
cout<<"<";
g.n
else
if(str1>str2)
cout<<">";
et
else
cout<<"="; str2.show();
}
getch();
}

Important Questions:
1. Distinguish between structured programming and object oriented programming. (4) [N/J–10]
2. Explain in detail, the structure of C++ program. (8)
3. Explain in detail, the following concepts of object oriented programming with an example:
a) Data abstraction (4)

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

b) Inheritance (4)
c) Polymorphism (4)
d) Objects (4)
4. Explain in detail, the function overloading with simple example. (8) [N/J–10] [M/J–13]
5. What is friend function and what are the merits and demerits of friend function? (8) [N/J–09]
6. What is a parameterized constructor? Write an example. (8) [N/J–09]
7. List out the purpose of constructor and destructor function. (6) [N/J–10]
8. Write short notes on constructor and destructor. (6) [M/J–13]
9. What is class string? Use overload ‘= =’ to distinguish between two strings. (8) [N/J–09]
10. What is operator overloading? Write a C++ program to overload the numerical operators “+”and “–
” for number respectively? (16) [A/M–10] [N/J–12]

ww
11. Write short notes on operator overloading. (8) [M/J–13]
12. Write a C++ program to illustrate operator overloading through friend functions. (8)

w.E
asy
En
gin
ee rin
g.n
et

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

DHANALAKSHMI COLLEGE OF ENGINEERING


DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING
EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
YEAR / SEM: II / 03 UNIT II
INHERITANCE & POLYMORPHISM
Part A

INHERITANCE

1. What is multiple inheritance? [N/D–12]


A class that inherits the attributes of two or more classes is known as multiple inheritance.
Base Classes

ww
A B

Derived class
C

w.EHere, derived class ‘C’ inherits from multiple base classes as A and B.
Syntax:

asy
class derived-class-name : visibility A, visibility B
{
…………………
}; En
// members of derived class

gin
Where, visibility may be either public or private.

2. What is inheritance?
ee [M/J–13]
The mechanism of deriving a new class from an old one is called inheritance. The old

rin
class is referred to as the base class and the new one is called the derived class or subclass that

in C++.
A (Parent) g.n
inherits some or all the attributes from base class. Inheritance provides the concept of reusability

B (Son)
Base class (Existing class)

Derived class (New class)


et
3. Write the advantages of inheritance.
The advantages of inheritance are:
1) Inheritance provides the concept of reusability in C++
2) Classes can be reused using inheritance
3) Classes can access the attributes of base classes

4. What are the types of inheritance?


The types of inheritance are:
1) Single inheritance

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

2) Multiple inheritance
3) Hierarchical inheritance
4) Multilevel inheritance
5) Hybrid inheritance

5. Define – Base Class and Derived Class


Base class is defined as the parent class that cannot be inherited from any other class.
Derived class is defined as a new class which is inherited from the base class.

A Base class (Parent)

B Derived class (Child)

6. Define – Single Inheritance

ww When a subclass inherits only from one base class, it is known as single inheritance.
A Base class

w.E
Syntax:
B Derived class

asy
class derived-class-name : visibility-mode base-class-name
{

En
………………… // members of derived class
};

7. Define – Multilevel Inheritance gin


derived class. A ee
Multilevel inheritance is defined as the mechanism of deriving a class from another
Base class
rin
g.n
B Subclass of A and Base class of C

C
Derived class

et
When a subclass inherits from a class that itself inherits from another class, it is known as
multilevel inheritance.

8. Define – Hierarchical Inheritance


Hierarchical Inheritance is defined as when more than one subclass inherits from single
base class. C Base class

A B Derived classes
Ahihf
yugug
9. Define – Hybrid
u Inheritance
Hybrid inheritance is defined as when a subclass inherits from multiple base classes and
its entire base classes inherit from a single base class.
A Base class

B C
Ahihf
yugug
u D
Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net

Subclass of A & Base Class of D

Sub class

10. What is a virtual base class?


When two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those objects by declaring
the base class as virtual when it is being inherited. Such a base class is known as virtual base
class. This can be achieved by preceding the base class’ name with the word virtual.

11. Differentiate inheritance from polymorphism. [N/D–10]

ww INHERITANCE POLYMORPHISM

w.E
1.
It refers to using the structure and behavior It refers to changing the behavior of a super class
of a super class in the sub class. in the sub class.

asy
Inheritance is when one class carries over Polymorphism is when you refer to something as

En
2.
the functionality of another. its base class.

3.
created from a base class. gin
It is the ability of a derived class to be It is the ability to override a base class to have
different forms.

ee rin
g.n
et

12. What is an abstract class? [N/D–09]


An abstract class is a class that cannot be instantiated and is usually implemented as a
class that has one or more pure virtual (abstract) functions. A pure virtual function is one which
must be overridden by any non-abstract derived class. This is indicated in the declaration with the
syntax " = 0" in the member function's declaration.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Example:
class AB
{
public:
virtual void f() = 0;
};

13. What is ‘this’ pointer? [N/D–09]


1) C++ uses unique keyword called ‘this’ to represent an object that invokes a member function.
2) This unique pointer is automatically passed to a member function when it is called.
3) The pointer ‘this’ act as an implicit argument to all the member functions.

14. How are pointers implemented in C++? [A/M–10]


A pointer is a variable whose value is the address of another variable. Like any

ww variable or constant, you must declare a pointer before you can work with it. The general form of
a pointer variable declaration is:

w.E type *var-name;


Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of
the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use
for multiplication.
Sample C++ program: asy
#include <iostream.h>
En
#include<conio.h>
void main ()
gin
{
clrscr();
int firstvalue, secondvalue;
ee rin
g.n
int * mypointer;
mypointer = &firstvalue; // first value is 10
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
et
// second value is 20

cout << "secondvalue is " << secondvalue << endl;


getch();
}
First, we have assigned as value of mypointer a reference to firstvalue using the reference operator
(&). And then we have assigned the value 10 to the memory location pointed by mypointer, that
because at this moment mypointer is pointing to the memory location of firstvalue, this in fact
modifies the value of firstvalue.

15. Define – Virtual Function [N/D–10]

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Virtual function is defined as the member function of a class that can be overridden in
its derived class. It is declared with virtual keyword. Virtual function call is resolved at run-time
(dynamic binding) whereas the non-virtual member functions are resolved at compile time (static
binding).

Part B

1. Explain the types of inheritance with example.


The mechanism of deriving a new class from an old one is called inheritance. The old class is
referred to as the base class and the new one is called as the derived class or subclass that inherits
some or all the attributes from base class. Inheritance provides the concept of reusability in C++.

ww Example C++ program:


#include<iostream.h>
#include<conio.h>

w.Eclass vehicle
{
public:
asy
vehicle(int wheels,int age);
~vehicle();
void print();
En
int wheels;
int age; gin
};
class bicycle : public vehicle
{
ee rin
public :
bicycle(int age, bool bell);
g.n
~bicycle();
void print();
bool has_bell();
et
void set_bell();
protected:
bool has_bell;
};
void main()
{
// function body
}
Inheritance : public
#include<iostream.h>
#include<conio.h>

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

class Polygon
{
protected:
int width,height;
public:
void setValues(int a, int b)
{
width=a;height=b;}};
class Rectangle: public Polygon
{
public:
int area()
{

ww return (width*height);}};
class Triangle: public Polygon
{

w.E
public:
int area()
{
asy
return (width*height/2);}};
void main()
{ En
int a,b; clrscr();
Rectangle rect; gin
Triangle trg;
ee
cout<<"\n**Simple Inheritance**\n";
cout<<"\nEnter the value of width:\t";cin>>a;
rin
cout<<"\nEnter the value of height:\t";cin>>b;
rect.setValues(a,b); g.n
trg.setValues(a,b);
cout<<"\n\nThe area of Rectangle is:\t"<<rect.area()<<endl;
cout<<"\nThe area of Triangle is:\t"<<trg.area()<<endl;
et
getch();
}

Different forms of inheritance:


1) Single inheritance
2) Multiple inheritance
3) Hierarchical inheritance
4) Multilevel inheritance
5) Hybrid inheritance
a) Single inheritance:
When a subclass inherits only from one base class, it is known as single inheritance.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

A Base class

Derived class
B

Syntax:
class derived-class-name : visibility-mode base-class-name
{
………………… // members of derived class
};

b) Multiple inheritance:
A class can inherit the attributes of two or more classes, is known as multiple
inheritance.

ww A B Base Class

w.E C Derived class

Here, derived class ‘C’ inherits from multiple base classes as A and B.
Syntax:
asy
class derived-class-name : visibility A, visibility B
{
………………… En
};
gin
// members of derived class

ee
Where, visibility may be either public or private.

Sample Program for Multiple Inheritance Using C++ Programming:


rin
// To Find Out the Student Details Using Multiple Inheritance
#include<iostream.h> g.n
{
#include<conio.h>
class student et
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :"; cin>>rno;
cout<<"Enter the two :";
cin>>m1>>m2;
}
};

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
{
cout<<"\nEnter the sports mark :";
cin>>sm;
}
};
class statement : public student, public sports
{

ww int tot,avg;
public:
void display()

w.E {
tot=(m1+m2+sm);

asy
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;

} En
cout<<"\n\tAverage : "<<avg;

};
void main() gin
{
statement obj;
obj.get();
ee rin
obj.getsm();
obj.display(); g.n
}
getch();

c) Hierarchical inheritance:
et
When more than one subclass inherits from single base class, it is known as Hierarchical
inheritance.
C Base class

A B Derived classes
Ahihf
yugug
u Hierarchical classification of students
Students

Arts Engineering Medical

CSE ECE IT Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Sample Program:
#include<iostream.h>
#include<conio.h>
class students
{
// function body
};
class arts : public students
{

ww // function body
};
class engg : public students

w.E{
// function body
};
asy
class ece : public engg
{
// function body En
};
class cse : public engggin
{
//function body
};
ee rin
class it : public engg
{ g.n
// function body
};

d) Multilevel inheritance:
et
1) The mechanism of deriving a class from another derived class is known as
Multilevel inheritance.
2) When a subclass inherits from a class that itself inherits from another class, it is
known as multilevel inheritance.

A Base class

B Subclass of A and Base class of C

C Derived class

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

e) Hybrid inheritance:
When a subclass inherits from multiple base classes and its entire base classes inherit
from a single base class.
A Base class

B C Subclass of A & Base Class of D


Ahihf
yugug
u D Sub class

Example:

student

ww test sports

w.E result

asy
Hybrid inheritance (Multiple and multilevel inheritance)

En
Sample C++ coding to illustrate the above example:
#include<iostream.h>
#include<conio.h>
class student gin
{
protected:
int rno;
ee rin
public:
void get_no(int a) g.n
{
rno = a;
}
et
void put_no(void)
{
cout<<”Roll No:”<<rno<<”\n”;
}
};
class test : public student
{
protected:
float part1,part2;
public:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

void get_marks(float x, float y)


{
part1=x; part2=y;
}
void put_marks(void)
{
cout<<”marks obtained”<<”Part1=”<<part1 <<”\n”<<”Part2=”<<part2<<”\n”;
}
};
class sports
{
protected:
float score;

ww public:
void get_score(float s)
{

w.E
score=s;
}

asy
void put_score(void)
{

En
cout<<”Sports weightage:”<<score<<”\n”;
}
};
gin
class result : public test, public sports
{
float total;
public:
ee rin
};
void display(void);
g.n
void result :: display(void)
{
total=part1+part2+score;
et
put_number();
put_marks();
put_score();
cout<<”Total Score=”<<total<<”\n”;
}
int main()
{
result r;
r.get_number(1234);
r.get_marks(12.4,44.3);

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

r.get_score(6.0);
return 0;
}

2. What is friend class? Explain with a suitable example.


Declare all the member functions of one class as the friend function of another class then it is
called a friend class. This can be specified as follows:
class z
{
…….
friend class x; // all member functions of x are friends to z
};

ww C++ allows some common functions to be made friendly with any number of classes, thereby
allowing the function to have access to the private data of these classes that need not to be a

w.E
member of any of these classes. Such common functions are called friend functions.
Sample program for friend function using C++ programming:
/* To find the mean value of a given number using friend function.*/

asy
#include<iostream.h>
#include<conio.h>
class base
{ En
int val1,val2;
public: gin
void get()
{ ee
cout<<"Enter two values:";
rin
}
cin>>val1>>val2;
g.n
};
friend float mean(base ob);

float mean(base ob)


et
{
return float(ob.val1+ob.val2)/2;
}
void main()
{
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

3. Explain Virtual function and pure virtual function.


Virtual function is the member function of a class that can be overridden in its derived class. It
is declared with virtual keyword. Virtual function call is resolved at run-time (dynamic binding)
whereas the non-virtual member functions are resolved at compile time (static binding).
Syntax:
class class-name
{
public:
virtual function-name
{

ww }
// function body

w.E };

Rules for virtual functions:

asy
When virtual functions are created for implementing late binding, it should satisfy the
following rules:

En
1) The virtual functions must be members of some class
2) They cannot be static members

gin
3) They are accessed by using object pointers
4) A virtual function can be a friend of another class

ee
5) A virtual function in a base class must be defined, even though it may not be used

rin
6) The prototypes of the base class version of a virtual function and all the derived class
versions must be identical

g.n
7) C++ cannot have virtual constructors, but it have virtual destructors

Example program for virtual functions:


#include<iostream.h>
#include<conio.h>
class base
et
{
public:
virtual void show()
{
cout<<"\n Base class show:";
}
void display()
{
cout<<"\n Base class display:" ;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

};
class drive:public base
{
public:
void display()
{
cout<<"\n Drive class display:";
}
void show()
{
cout<<"\n Drive class show:";
}};
void main()

ww {
clrscr();
base obj1;

w.E base *p;


cout<<"\n\t P points to base:\n" ;
p=&obj1;
p->display(); asy
p->show();
En
cout<<"\n\n\t P points to drive:\n";
drive obj2;
p=&obj2; gin
}
p->display();
p->show(); getch(); ee rin
4. What is polymorphism? Explain with an suitable example. g.n
et
Polymorphism means “having many forms”. It allows different objects to respond to the same
message in different ways, the response specific to the type of the object. The concept of
polymorphism is implemented using overloaded functions and operators.
a) Operator overloading
b) Function overloading
Operator overloading:
1) The process of making an operator to exhibit different behaviors in different instances is
known as Operator overloading.
2) It is the method of polymorphism.
Defining operator overloading:
It can be defined with a special function ‘operator’.
Syntax:
return-type class-name :: operator op(arg_list)

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
// function body
}

a) Overloading unary operator:


Unary takes one operand and one operator.
Syntax: object operator (or) operator object
Example: S++; (or) ++S;
b) Overloading binary operator:
The operators that act upon two operands are called binary operators. The binary
operators used in C++ are +, -, *, / , %, =. The binary overloaded operator function takes
the first object as an implicit operand and the second operand must be passed explicitly.
Syntax:

ww return-type operator operator-symbol(argument)


{
// function body

w.E }
Function overloading:

asy
To perform different types of tasks or functions using a single function name is known as
Function overloading.
Example:
En
add() is a overloaded function that handles different types of data as shown in below,

gin
// Function declarations
int add(iint, int);

ee
int add(int, int, int);
int add(double,double);
rin
g.n
et

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

DHANALAKSHMI COLLEGE OF ENGINEERING


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES

UNIT III
LINEAR DATA STRUCTURES
PART A

1. What is meant by data structure?


A data structure is a mathematical or logical way of organizing data in the memory that
considers not only the items stored but also the relationship to each other. It is characterized by

ww
accessing functions.

2. List out the areas in which data structures are applied extensively.

w.EThe areas in which data structures are as follows,


1) Operating system

asy
2) Computer networks
3) Mathematics uses queuing theory
4) Simulation
En
3. Define – Algorithm
gin
Algorithm is defined as a solution to a problem that consists of set of finite steps. When

time. ee
carried out for a given set of inputs, it produces the corresponding output and terminates in a finite

rin
4. Define – Program
g.n
Program is defined as an organized list of instructions, that when executed, causes

et
the computer to behave in a predetermined manner. Without programs, computers are useless.
A program is like a recipe. It contains a list of ingredients (called variables) and a list of
directions (called statements) that tell the computer what to do with the variables. The variables can
represent numeric data, text, or graphical images.

5. What are the different types of data structure?


The types of data structure are:
1) Primitive data structure
Example: int, char, float
2) Non primitive data structure
a) Linear data structures – Example: list, stack, queue
b) Non linear data structures – Example: trees, graphs

6. Define – Linear Data Structure

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Linear data structure is defined as the data structure in which data is arranged in a list
or in a straight sequence.
Example: List, stack, queue.

7. List out the operations of ADT.


The operations of ADT are:
1) Find(X) – Return the position of X
2) Printlist – Contents of the list is displayed
3) Make empty – Makes the list empty
4) Insert(X,5) – Insert the element X after the position 5
5) Delete(X) – Delete the element X
6) Previous(i) – Return the position of its predecessor, i – 1
7) Next(i) – Return the position of its successor, i + 1

ww
8. Differentiate linear data structure from nonlinear data structure.

w.E
Linear data structure Nonlinear data structure

asy
They are linear relationship between its They do not have a linear relationship between
adjacent elements. its adjacent elements.

En
Example: Linked list, Stack, Queue Example: Tree, Graphs.

9. Define – Abstract Data Type


gin [M/J–07] [N/D–09] [N/D–10]
Abstract data type is defined as a set of operations that refers a data type such as union,
intersection, complement, find etc.,
ee rin
ADT is a triple of domains and functions. In ADT, all the implementation details are hidden.
ADT = Type + Function names + Function behavior

10. Differentiate array from list. g.n


Array
Size of an array is fixed. Size of list is unfixed. et
List

Necessary to specify the number of elements Not necessary to specify the number of elements
during declaration. during declaration.

Insertion and deletions are difficult. Insertion and deletions are easy.
Array occupies less memory. Occupies more memory.

11. What is an ordered list?


An ordered list is a set of elements where set may be empty or it can be written as a collection
of elements such as a1,a2,a3…..an called a linear list.
Example: List of one digit numbers – (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

12. What are the different ways to implement list?

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

The different ways to implement list are:


1) Static implementation (Using Arrays)
2) Dynamic implementation (Using Linked list)
3)

13. What is the concept of push and pop in a linked stack? [N/D–09]
Push – Insert an element into the stack
Pop – Delete an element from the stack

14. List out the applications of stack. [N/D–09]


The applications of stack are:
1) Expression conversion
2) Expression evaluation

ww 3) Parsing well formed parenthesis


4) Decimal to binary conversion

w.E 5) Reversing a string


6) Storing function calls

asy
15. Differentiate stack from queue.
Stack Queue
[N/D–11]

En
Stack is LIFO data structure (Last In First Out) Queue is FIFO data structure (First In First Out)

top of the stack. gin


Insertion, deletion is restricted to one end that is Insertion and deletion performed at two different
ends that are front and rear.

ee
After the deletion, the top of the stack is
decremented.
rin
After the deletion front is incremented.

g.n
16. Define – Stack
et
A stack is defined as an ordered collection of items into which new items may be inserted
and from which items may be deleted at one end, called the top of the stack. The other name of
stack is Last-In-First-Out (LIFO) list.

17. Define – Dequeue


Dequeue is defined as the process of deleting an element from the queue.

Dequeue (Q) Enqueue (Q)


Queue Q
Front Rear

18. List out the applications of queue.


The applications of queue are:
1) Jobs submitted to printer
2) Real life line

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

3) Calls to large companies


4) Access to limited resources in Universities
5) Accessing files from file server

19. What is Queue?


Queue is FIFO data structure (First In First Out). Insertion and deletion performed at two
different ends that are front and rear. After the deletion front is incremented.
“A queue is an ordered list in which all insertions at one end called REAR and deletions are
made at another end called FRONT”. Queues are sometimes referred to as First In First Out
(FIFO) lists. enqueue
(Insertion)

ww
w.E dequeue

asy
(Deletion) Front Rear

En
gin
ee rin
g.n
et

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Part -B
1. Explain Array representation of list ADT.
Basic Idea:
1) Pre-allocate a big array of size MAX_SIZE
2) Keep track of current size using a variable count
3) Shift elements when you have to insert or delete
A1 A2 A3 A4 … AN
0 1 2 3 … count-1 MAX_SIZE-1
Coding:
#include<iostream.h>
#include<conio.h>
#include<process.h>

ww void create();
void insert();

w.E
void deletion();
void search();
void display();

asy
int a,b[20],n,d,e,f,i;
void main()
{
int c; En
char g='y';
clrscr(); gin
do
{
cout<<"\n Main Menu";
ee rin
g.n
cout<<"\n 1.Create \n 2.Delete \n 3.Search \n 4.insert \n 5.Display \n 6.Exit";
cout<<"\n enter your choice\n";
cin>>c;
switch(c)
{
et
case 1: create(); break;
case 2: deletion(); break;
case 3: search(); break;
case 4: insert(); break;
case 5: display(); break;
case 6: exit(0); break;

default:
cout<<"The given number is not between 1-5\n";
}
cout<<"\nDo u want to continue \n";

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

cin>>g;
clrscr();
}
while(g=='y'|| g=='Y');
getch();
}
void create()
{
cout<<"\n Enter the number\n";
cin>>n;
for(i=0;i<n;i++)
{

ww
cin>>b[i];
}}
void deletion()
{
w.E
cout<<"Enter the limit u want to delete \n";
cin>>d;
for(i=0;i<n;i++)asy
{
if(b[i]==d)
En
{
b[i]=0; gin
}}}
void search()
{
ee rin
cout<<"Enter the limit \n";
cin>>e;
g.n
for(i=0;i<n;i++)
{
if(b[i]==e)
et
{
cout<<"Value found the position\n"<<b[i];
}}}
void insert()
{
cout<<"enter how many number u want to insert \n";
cin>>f;
for(i=0;i<f;i++)
{
cin>>b[n++];
}}
void display()

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
cout<<"\n\n\n";
for(i=0;i<n;i++)
{
cout<<"\n\n\n"<<b[i];
}}

2. Explain Circular linked list.


Circular list is a list in which the link field of the last node is made to point to the start/first
node of the list.

ww
w.E
Insertion In Circular Linked List:

asy
There are three situations for inserting element in Circular linked list:
1. Insertion at the front of Circular linked list.

En
2. Insertion in the middle of the Circular linked list.
3. Insertion at the end of the Circular linked list.

gin
1. Insertion at the front of Circular linked list
Procedure for insertion a node at the beginning of list:
Step1. Create the new node
ee
Step2. Set the new node’s next to itself (circular)
Step3. If the list is empty, return new node rin
Step4. Set our new node’s next to the front
Step5. Set tail’s next to our new node g.n
Step6. Return the end of the list
et

Algorithm for Insertion at the front of Circular linked list


node* AddFront(node* tail, int num)

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

{
node *temp = (node*)malloc(sizeof(node));
temp->data = num;
temp->next = temp;
if (tail == NULL)
return temp;
temp->next = tail->next;
tail->next = temp;
return tail;
}

2. Insertion in the middle of the Circular linked list


InsertAtlocDll(info,next,start,end,loc,size)
1.set nloc = loc-1 , n=1

ww2.create a new node and address in assigned to ptr.


3.check[overflow] if(ptr=NULL)
write:overflow and exit

w.E
4.set Info[ptr]=item;
5.if(start=NULL)
set next[ptr] = NULL
set start = ptr
else if(nloc<=size) asy
En
repeat steps a and b while(n != nloc)

gin
a. loc = next[loc]
b. n = n+1
[end while]

else
next[ptr] = next[loc]
next[loc] = ptr ee rin
set last = start;
repeat step (a) while(next[last]!= NULL)
g.n
[end if]
a. last=next[last]
[end while]
last->next = ptr ; et
6.Exit.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

3. Insertion at the end of Circular linked list


Procedure for insertion a node at the end of list:
Step1. Create the new node
Step2. Set the new node’s next to itself (circular)
Step3. If the list is empty,return new node
Step4. Set our new node’s next to the front
Step5. Set tail’s next to our new node
Step6. Return the end of the list

ww
w.E
Algorithm for Insertion at the End of Circular linked list:

{
asy
node* AddEnd(node* tail, int num)

node *temp = (node*)malloc(sizeof(node));


temp->data = num;
temp->next = temp; En
if (tail == NULL)
gin
return temp;

}
temp->next = tail->next;
tail->next = temp;
return temp; ee rin
Deletion In Circular linked list g.n
There are three situations for Deleting element in list:
1. Deletion at beginning of the Circular linked list
2. Deletion at the middle of the Circular linked list
et
3. Deletion at the end of the Circular linked list

1. Deletion at beginning of the Circular linked list:

After Deletion

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

2. Deletion at the middle of the Circular linked list:

ww
After Deletion

w.E
asy
En
gin
Deletion at the end of the Circular linked list

ee rin
g.n
et
After Deletion

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

3. Explain Singly linked list.

Linked List:
1) An ordered sequence of nodes with links
2) The nodes do not reside in sequential locations
3) The locations of the nodes may change on different runs

Singly Linked List:


In this type of linked list two nodes are linked with each other in sequential linear manner.
Movement in forward direction is possible.

ww
w.E
asy
Inserting a node or element into Linked list :
Inserting an element into linked list contains 3 types.
1. Insertion at beginning of the Linked list

En
2. Insertion at the middle of the linked list

gin
3. Insertion at the end of the linked list
1. Insertion at beginning of the Linked list :

ee
An element can be inserted at the beginning of the Linked list by creating a new node at
the beginning of the linked list and inserting an element into the node and assigning the

rin
address of the address of the next node or assigning the reference of the next node.
2. Insertion at the middle of the linked list :

g.n
An element can be inserted at the middle of the linked list. We need to know the data or

et
element of the neighboring element to insert an element at middle.
3. Insertion at the End of the linked list :
An element can be inserted at the end by simply traversing the node to the end and
creating a new node at the end. Also the address pointer of the new node must be assigned to
NULL.
Procedure for inserting an element to linked list:
Step-1: Get the value for NEW node to be added to the list and its position
Step-2: Create a NEW, empty node by calling malloc(). If malloc() returns no error then go to
step-3 or else say "Memory shortage"
Step-3: Insert the data value inside the NEW node's data field
Step-4: Add this NEW node at the desired position (pointed by the "location") in the LIST
Step-5: Go to step-1 till you have more values to be added to the LIST

Insertion Node in Linked List


void insert(node *ptr, int data)

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

/* Iterate through the list till we encounter the last node.*/

while(ptr->next!=NULL)

ptr = ptr -> next;

/* Allocate memory for the new node and put data in it.*/

ptr->next = (node *)malloc(sizeof(node));

ptr = ptr->next;

ww
ptr->data = data;

ptr->next = NULL;

w.E
}

Insertion at the front of list

asy
En
gin
ee rin
Insertion Node in given location Linked List:
g.n
et

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Insertion at the end of the list:

Deleting a node from the Linked list:

ww Deleting an element is similar to pop operation in Stack and Queue. A node can be deleted in
3 ways similar to Insertion.

w.E 1. Deleting a Node from the beginning of the Linked List


2. Deleting a node from the middle of the Linked list
3. Deleting a node from the end of the Linked List

Single Linked List asy


En
gin
ee rin
Deletion Node 30 in Single Linked List g.n
et
After Deletion Linked List

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

4. Explain Double linked list.


In a simple linked list, there will be one pointer named as 'NEXT POINTER' to point the
next element, where as in a doubly linked list, there will be two pointers one to point the next
element and the other to point the previous element location.
A node in a doubly linked list stores two references -- a next link, which points to the next
node in the list, and a prev link, which points to the previous node in the list.

ww
Insertion/Deletion:

w.E Insertion or deletion at the first node or the last node would be relatively easy with the
introduction of both the prev and next link. Look at the above figure, it demonstrates the process

asy
of adding/removing an element at either ends.

En
gin
Algorithm addFirst(v):
ee rin
w = header.getNext() // the current first node
v.setNext(w) g.n
w.setPrev(v)
header.setNext(v)
v.setPrev(header)
et
size++

Algorithm removeLast():
v = trailer.getPrev() // the current last node
if (v = = header) then
Indicate an error: the list is empty
prev = v.getPrev()
prev.setNext(trailer)
trailer.setPrev(prev)
v.setPrev(null)
v.setNext(null)
size—

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Insertion in the middle of a linked list, which might be difficult to implement on a singly
linked list, but easy to implement on a doubly linked list.
The two-way linking makes a doubly linked list convenient for maintaining a list of
elements while allowing for insertion and removal in the middle of the list.
Given a node v of a doubly linked list, we can easily insert a new node z immediately after
v.
Algorithm addAfter(v, z):
w = v.getNext()
v.setNext(z)
z.setPrev(v)
z.setNext(w)
w.setPrev(z)

ww
Advantages:
size++

1) We can traverse in both directions i.e. from starting to end and as well as from end to

w.E
starting.
2) It is easy to reverse the linked list.

asy
3) If we are at a node, then we can go to any node. But in linear linked list, it is not possible
to reach the previous node.
Disadvantages:
En
1) It requires more space per space per node because one extra field is required for pointer
to previous node.
gin
2) Insertion and deletion take more time than linear linked list because more pointer

ee
operations are required than linear linked list.

rin
g.n
5. Explain in detail, the Stack.
et
“A stack is an ordered list in which all insertions and deletions are made at one end, called the
top”. Stacks are sometimes referred to as Last In First Out (LIFO) lists.
Stacks have some useful terminology associated with them:
 Push To add an element to the stack
 Pop To remove an element from the stack
 LIFO Refers to the last in, first out behavior of the stack
The operations of stack are,
1. PUSH operations
2. POP operations
Push (n): Inserts the item n at the top of stack

Pop (): Removes the top element from the stack and returns that top element. An error occurs
if the stack is empty.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

1. Adding an element into a stack. (Called PUSH operations)


Adding element into the TOP of the stack is called PUSH operation.
Check conditions:
TOP = N, then STACK FULL Where N is maximum size of the stack.
Implementation in C using array:
void push (int item)
{
if (top == size-1)
printf(“Stack is Overflow”);
else
{
top = top + 1;

ww }
}
stack[top] = item;
item /
element 6

w.E
Stack Stack

asy PUSH
operation
top 6
8
8
En
top

4 4
gin
ee
2. Deleting an element from a stack. (Called POP operations)

rin
Deleting or Removing element from the TOP of the stack is called POP operations.

g.n
Check Condition:
TOP = 0, then STACK EMPTY et
Deletion in stack (POP Operation)
Implementation in C using array:
int pop ( )
{
if (top == -1)
{
printf(“Stack is Underflow”);
return (0);
}
else
{

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

return (stack[top--]);
}} item /
element
6

top 6 POP
operation
8 top 8
4
4
Stack
Stack
Application of Stack:

ww 1) It is very useful to evaluate arithmetic expressions. (Postfix Expressions)


2) Infix to Postfix Transformation
3) It is useful during the execution of recursive programs

w.E
4) A Stack is useful for designing the compiler in operating system to store local variables
inside a function block

asy
5) A stack can be used in function calls including recursion
6) Reversing Data
7) Reverse a list
8) Convert Decimal to Binary
En
gin
9) Parsing – It is a logic that breaks into independent pieces for further processing
10) Backtracking

ee
6. Explain in detail, the applications of stack.

rin
1. EVALUATION OF AN EXPRESSION: (Expression evaluation and syntax parsing)

g.n
Calculators employing reverse Polish notation (also known as postfix notation) use a
stack structure to hold values.

et
Expressions can be represented in prefix, postfix or infix notations. Conversion from one
form of the expression to another form needs a stack. Many compilers use a stack for parsing the
syntax of expressions, program blocks etc. before translating into low level code.
Most of the programming languages are context-free languages allowing them to be
parsed with stack based machines. Note that natural languages are context sensitive languages
and stacks alone are not enough to interpret their meaning.

Infix, Prefix and Postfix Notation


We are accustomed to write arithmetic expressions with the operation between the two
operands: a+b or c/d. If we write a+b*c, however, we have to apply precedence rules to avoid
the ambiguous.
Infix Prefix Postfix
a+b +ab ab+

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

a+b*c +a*bc abc*+


(a + b) * (c - d) *+ab-cd ab+cd-*
b*b-4*a*c
40 - 3 * 5 + 1

Examples of use: (application of stack)


Arithmetic Expressions: Polish Notation
An arithmetic expression will have operands and operators. Operator precedence listed
below:
Highest : ($)
Next Highest : (*) and (/)

ww Lowest : (+) and (-)


1) For most common arithmetic operations, the operator symbol is placed in

w.E between its two operands. This is called infix notation.


Example: A + B, E * F
2) Parentheses can be used to group the operations.

asy
Example: (A + B) * C
Accordingly, the order of the operators and operands in an arithmetic expression does not

En
uniquely determine the order in which the operations are to be performed.

gin
Polish notation refers to the notation in which the operator symbol is placed before its
two operands. This is called prefix notation.
Example: +AB, *EF
ee rin
The fundamental property of polish notation is that the order in which the operations are
to be performed is completely determined by the positions of the operators and operands in the

g.n
expression. Accordingly, one never needs parentheses when writing expressions in Polish
notation.

et
Reverse Polish Notation refers to the analogous notation in which the operator symbol
is placed after its two operands. This is called postfix notation.
Example: AB+, EF*
Here also the parentheses are not needed to determine the order of the operations.
The computer usually evaluates an arithmetic expression written in infix notation in two
steps,
1. It converts the expression to postfix notation.
2. It evaluates the postfix expression.
In each step, the stack is the main tool that is used to accomplish the given task.

2. BALANCING PARANTHESIS:
Procedure:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Given an expression string exp, write a program to examine whether the pairs and the
orders of “{“,”}”,”(“,”)”,”[","]” are correct in exp. For example, the program should print true for
exp = “[()]{}{[()()]()}” and false for exp = “[(])”

Algorithm:
1) Declare a character stack S.
2) Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[') then push it to stack.++
b) If the current character is a closing bracket (')' or '}' or ']‘) then pop from stack and if
the popped character is the matching starting bracket then fine else parenthesis are not
balanced.
3) After complete traversal, if there is some starting bracket left in stack then “not balanced”

ww
C++ Program to check for balanced parentheses in an expression using stack:

w.E
Given an expression as string comprising of opening and closing characters of parentheses - (),
curly braces - {} and square brackets - [], we need to check whether symbols are balanced or not.
#include<iostream>
#include<stack>
#include<string> asy
using namespace std;
En
gin
// Function to check whether two characters are opening
// and closing of same type.

ee
bool ArePair(char opening,char closing)
{ if(opening == '(' && closing == ')') return true;
else if(opening == '{' && closing == '}') return true;
else if(opening == '[' && closing == ']') return true; rin
}
return false;
g.n
bool AreParanthesesBalanced(string exp)
{
stack<char> S;
et
for(int i =0;i<exp.length();i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
S.push(exp[i]);
else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
{
if(S.empty() || !ArePair(S.top(),exp[i]))
return false;
else
S.pop();
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

}
return S.empty() ? true:false;
}
int main()
{
/*Code to test the function AreParanthesesBalanced*/
string expression;
cout<<"Enter an expression: "; // input expression from STDIN/Console
cin>>expression;
if(AreParanthesesBalanced(expression))
cout<<"Balanced\n";
else

ww }
cout<<"Not Balanced\n";

w.E
Self-check:
Trace the execution of function IsBalanced for each of the expressions below. Your trace

asy
should show the stack after each push or pop operation. Also show the values of Balanced,
Open, and Close after each close parenthesis is processed.

En
(a + b * {c / [d - e]}) + (d / e)
(a + b * {c / [d - e}}) + (d / e)

gin
ee rin
7. Explain in detail, the QUEUE.
g.n
(FIFO) lists. enqueue
et
“A queue is an ordered list in which all insertions at one end called REAR and deletions
are made at another end called FRONT”. Queues are sometimes referred to as First In First Out

(Insertion)

dequeue
Front Rear
(Deletion)

Example:
1. The people waiting in line at a bank cash counter form a queue.
2. In computer, the jobs waiting in line to use the processor for execution. This queue is
called Job Queue.
Operations of Queue:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

There are two basic queue operations. They are,


Enqueue – Inserts an item / element at the rear end of the queue. An error occurs if the
queue is full.
Dequeue – Removes an item / element from the front end of the queue, and returns it to
the user. An error occurs if the queue is empty.

1. Addition into a queue:


procedure addq (item : items);
{add item to the queue q}
begin
if rear=n then queuefull
else begin

ww
rear :=rear+1;
q[rear]:=item;
end;

w.E end;{of addq}


2. Deletion in a queue :

asy
procedure deleteq (var item : items);
{delete from the front of q and put into item}
begin
En
if front = rear then queueempty
else begin
front := front+1 gin
end
end;
item := q[front];
ee rin
Uses of Queue (Application of queue):
g.n
Queue remember things in first-in-first-out (FIFO) order. Good for fair (first come first served)
ordering of actions.

8. Circular queue:
et
In a circular queue, locations of queue are viewed in a circular form. The first location is
viewed after the last one. Overflow occurs when all the locations are filled.

rear

front

Algorithm Circular Queue Insert:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Void CQInsert ( int queue[ ], front, rear, item)


{
if ( front = = 0 )
front = front +1;
if ( ( ( rear = maxsize ) && ( front = = 1 ) ) || ( ( rear ! = 0 ) && ( front = rear +1)))
{
printf( “ queue overflow “);

if( rear = = maxsize )


rear = 1;
else
rear = rear + 1;

ww }
}
q [ rear ] = item;

w.E
Algorithm Circular Queue Delete:
int CQDelete ( queue [ ], front, rear )
{
if ( front = = 0 ) asy
else
En
printf ( “ queue underflow “);

{
gin
item = queue [ front ];
if(front = = rear )
{
front = 0; rear = 0;
ee rin
}
else if ( front = = maxsize )
g.n
else
{front = 1;}

front = front + 1;
et
}
return item;
}

Important Questions:
1. Explain in detail, the array representation of list with algorithm. (16)
2. Explain in detail, the algorithm for creation, insertion, deletion and searching in circular linked
list. (16)
3. What is singly linked list? Explain in detail, insertion, deletion and searching operation in
singly linked list.
4. What is double linked list? Explain in detail, the various operations of double linked list with
algorithm. (16) [N/D–09]

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

5. Write an algorithm for inserting an element and deleting an element in a linked list.
(8) [A/M–11]
6. Write a C++ program to implement stack operations PUSH and POP. (8) [A/M–10]
7. Explain in detail, the operations performed by stack. Write a C++ program to implement these
operations. (8) [N/D–11]
8. What is stack ADT? Explain in detail, the array implementation of stack. (16)
9. Explain in detail, the procedure to check the parentheses balancing in an expression using stack.
(16)
10. Explain in detail, any two applications of stack along with its implementations. (16)
11. Write algorithms to insert an element into a stack and a queue. (8)
12. Explain in detail, the algorithm to insert and delete an element in a queue. (16)
13. Explain in detail, the ADT operations for circular queue with suitable examples. (16)

ww
w.E
asy
En
gin
ee rin
g.n
et

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

DHANALAKSHMI COLLEGE OF ENGINEERING


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
UNIT IV
NONLINEAR DATA STRUCTURES
Part A

1. Define – Tree [N/D–08]


Tree is a non-liner data structure, which is used to store data item in a shorted
sequence. It represents any hierarchical relationship between any data item. It is a collection
of nodes, which has a distinguished node called root node and zero or more non-empty sub

ww trees T1, T2….Tk, each of which are connected by a directed edge from the root.

2. Define – Full Binary Tree [A/M–07]

w.E A full binary tree (sometimes 2-tree or strictly binary tree) is a tree in which
every node other than the leaves has two children. A full tree is sometimes ambiguously

asy
defined as a perfect tree. Physicists define a binary tree to mean a full binary tree. A binary
tree T is full if each node is either a leaf or possesses exactly two child nodes.

3. Define – Complete Binary Tree


En [A/M–07]

gin
A complete binary tree is a binary tree in which every level, except possibly the
last, is completely filled, and all nodes are as far left as possible. A tree is called an almost

ee
complete binary tree or nearly complete binary tree if the exception holds, i.e. the last level
is not completely filled. This type of tree is used as a specialized data structure called a
heap.
rin
g.n
A binary tree T with n levels is complete if all levels except possibly the last are
completely full and the last level has all its nodes to the left side.

4. State the properties of a binary tree.


The properties of binary tree the properties of binary tree are:
et [N/D–09]

1) A binary tree of n elements has n-1 edges


2) A binary tree of height h has at least h and at most 2h - 1 elements
3) The height of a binary tree with n elements is at most n and at least log2 (n+1)

5. Define – Binary Tree [N/D–09]


Binary tree is a finite set of elements that is either empty or is partitioned into three
disjoint subsets. The first subset contains a single element called the root of the tree. The
other two subsets are themselves binary trees called the left and right sub trees.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

6. What is a threaded binary tree? [N/D–10]


A Threaded Binary Tree is a binary tree in which every node that does not have a right
child has a THREAD (in actual sense, a link) to its INORDER successor. By doing this
threading we avoid the recursive method of traversing a Tree, which makes use of stacks and
consumes a lot of memory and time.

7. Write an algorithm to declare node of a tree structure. [A/M–10]

ww Algorithm to declare node of a tree structure:


typedefstruct node

w.E {
int data;
struct node *left;

asy
struct node *right;
}bin;

En
8. Write an example for expression tree. [A/M–10]
(A+B)*((C-D)/(E^F))
gin
ee rin
g.n
9. List out the advantages of a threaded binary tree.
et
[N/D–09]
The advantages of a threaded binary tree are:
1) By doing threading we avoid the recursive method of traversing a Tree , which
makes use of stack and consumes a lot of memory and time .
2) The node can keep record of its root.

10. Define – Expression Tree [N/D–09]


Expression tree is also a binary tree in which leaf nodes are terminal nodes or
operands and non-terminal intermediate nodes are operators used for traversal.
Example:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

11. Differentiate Graph from Tree. [N/D–11]


1) A tree is a specialized case of a graph. A tree is a connected graph with no circuits and
no self-loops.
2) A graph G consists of a nonempty set V which is a set of nodes of the graph, a set E
which is the set of edges of the graph, and a mapping from the set for edge E to a set of

ww pairs of elements of V.

12. Define – Non-linear Data structure

w.E Non Linear data structures are data structures that have a linear relationship between its
adjacent elements but it has the hierarchical relationship.

asy
Example: Graph, Tree.

13. List out the applications of tree data structure.

En
The applications of tree data structure are:

gin
1) On a computer - The file scheme uses tree architecture; a list of options system also
has the same idea of selecting radical strata of options.
2) Indexes in a book have a narrow tree structure - letter/subjects starting with that

ee
letter. Contents probably have a superior layout - the different levels of chapters.

rin
3) In computer science, a tree is a commonly used data formation that feigns a
hierarchical tree structure with a set of linked nodes.

14. Define – Leaf g.n


et
Nodes with no children are known as leaves. A leaf will always have degree zero and
is also called terminal node.

15. What is node level?


The level of a node is defined recursively by assuming the level of the root to be one
and if a node is at level ‘l’, then its children at level ‘l+1’.

16. Define – Degree of a Node


It is the number of sub trees of a node in a given tree.

17. Define – Siblings


Nodes with the same parent are called siblings.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

18. Define – Height


The height of a node n is the length of the longest path from root to a leaf. Thus all
leaves have height zero. The height of a tree is equal to a height of a root.

19. What is meant by path length in a tree?


The path length in tree is a number of edges between nodes from the root to the node. The
depth of a tree is the length of the longest path from the root to leaf node.

20. Define – Forest


A forest is a disjoint union of trees. A forest is a collection on N (N>0) disjoint tree
or group of trees. If the root is removed from the tree, that tree becomes a forest.

ww
21. What is an ordered tree?
An ordered tree is an oriented tree in which the children of a node are somehow "ordered."

w.E
asy
If T1 and T2 are ordered trees then T1 ≠ T2 else T1 = T2.

En
22. What are the applications of binary tree?
The applications of binary tree are:

gin
1) Used in almost every high-bandwidth router for storing router-tables.
2) Used in Huffman code construction.

23. What is meant by traversing?


ee
3) Used in parse tree construction.

rin
g.n
Traversing a tree means processing it in such a way, that each node is visited only once.
Traversal is an operation which can be performed on a binary tree is visiting all the nodes
exactly once.

24. What are the different types of traversals?


The different types of traversing are:
et
1) Pre-order traversal-yields prefix form of expression
2) In-order traversal-yields infix form of expression
3) Post-order traversal-yields postfix form of expression

25. What are the two methods of binary tree implementation?


The two methods of binary tree implementation are:
1) Array or sequential representation
2) Linked list representation

26. What are the various operations of binary trees for link representation?

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

The various operations of binary trees for link representation are:


1) Creation of binary tree
2) Insertion of a node in the tree
3) Display of a binary tree

27. Define – Pre-order Traversal


To traverse a binary tree in Pre-order, the following operations are carried-out
1) Visit the root
2) Traverse the left subtree
3) Traverse the right subtree

28. Define – Post-order Traversal


To traverse a binary tree in Post-order, the following operations are carried-out

ww 1) Traverse the left subtree


2) Traverse the right subtree

w.E
3) Visit the root

29. Define – In-order Traversal

asy
To traverse a binary tree in In-order, the following operations are carried-out
1) Traverse the left subtree
2) Visit the root
En
3) Traverse the right sub tree

gin
ee
30. What is meant by binary search tree?
rin[N/D–09][N/D–11]
A binary search tree is also known as an ordered binary tree which is a node-based

g.n
data structure in which each node has no more than two child nodes. Each child must either

et
be a leaf node or the root of another binary search tree.
The left sub-tree contains only nodes with keys less than the parent node and the
right sub-tree contains only nodes with keys greater than the parent node.

31. Define – Binary Search Tree


Binary search tree is a special binary tree, which is either empty or should satisfy
the following characteristics:
1) Every node has a value and no two nodes should have the same value i.e. the
values in the binary search tree are distinct.
2) The value in any left sub-tree is less than the value of its parent node.
3) The value in any right sub-tree is greater than the value of its parent node.
4) The left and right sub-trees of each node are again binary search trees

32. Write an algorithm to find, insert and delete nodes in binary search tree.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Algorithm for insertion in Binary Search Tree:


If key [x] < v move to the right child of x,
else move to the left child of x
When x is NIL, we found the correct position
If v < key [y] insert the new node as y’s left child
else insert it as y’s right child
Algorithm for deletion in Binary Search Tree:
if left[z] = NIL or right[z] = NIL
then y ← z
else y ← TREE-SUCCESSOR(z)
if left[y]  NIL
then x ← left[y]
else x ← right[y]

ww if x  NIL
then p[x] ← p[y]

w.E if p[y] = NIL


then root[T] ← x

asy
else if y = left[p[y]]
then left[p[y]] ← x
else right[p[y]] ← x
if y  z
En
then key[z] ← key[y]
gin
copy y’s satellite data into z
return y
ee rin
33. Define – Graph
g.n
[N/D–06] [N/D–07]
A graph G consist of a nonempty set V which is a set of nodes of the graph, a set E

et
which is the set of edges of the graph, and a mapping from the set for edge E to a set of
pairs of elements of V. It can also be represented as G= (V, E).

NONLINEAR DATA STRUCTURES


Part B
1. Explain the concept of binary tree with example.

A tree is a set of nodes which is either null or with one node designated as the root and
the remaining nodes partitioned into smaller trees, called sub-trees. The level of a node is the
length of the path from the root to that node,
 The depth of a tree is the maximum level of any node of any node in the tree

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

 The degree of a node is the number of partitions in the subtree which has that node
as the root
 Nodes with degree=0 are called leaves
Binary tree is a tree in which the maximum degree of any node is 2. Binary tree is a
finite set of elements that is either empty or is partitioned into three disjoint subsets. The first
subset contains a single element called the root of the tree. The other two subsets are
themselves binary trees called the left and right sub trees.

wwThe properties of binary tree the properties of binary tree are:


4) A binary tree of n elements has n-1 edges

w.E 5) A binary tree of height h has at least h and at most 2h - 1 elements


6) The height of a binary tree with n elements is at most n and at least log2 (n+1)

Tree Traversal Algorithms:


asy
Traversing a tree means processing it in such a way, that each node is visited only once.

En
Traversal is an operation which can be performed on a binary tree is visiting all the nodes

gin
exactly once.
The different types of traversing are:
4) Pre-order traversal-yields prefix form of expression

ee
5) In-order traversal-yields infix form of expression
6) Post-order traversal-yields postfix form of expression
1. In-order: rin
1. Traverse left subtree
2. Visit node (i.e. process node) g.n
3. Traverse right subtree
2. Preorder:
1. Visit node
et
2. Traverse Left
3. Traverse right
3. Post-order:
1. Traverse left
2. Traverse right
3. Visit node
Example:
An arithmetic expression tree stores operands in leafs, operators in non-leaf nodes:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

In-order traversal: (LNR) A-B+C/D*E-F


Post-order traversal: (LRN) AB-C/EF-*+
Pre-order traversal: (NLR) +-AB*/CD-EF
Applications:
The applications of binary tree are:

ww 4) Used in almost every high-bandwidth router for storing router-tables


5) Used in Huffman code construction

w.E 6) Used in parse tree construction

2. Explain the concept of binary search tree with example.

asy
A binary search tree is also known as an ordered binary tree which is a node-based
data structure in which each node has no more than two child nodes. Each child must either

En
be a leaf node or the root of another binary search tree.
The left sub-tree contains only nodes with keys less than the parent node and the

gin
right sub-tree contains only nodes with keys greater than the parent node.
Characteristics:
ee
Binary search tree is a special binary tree, which is either empty or should satisfy
the following characteristics:
rin
g.n
5) Every node has a value and no two nodes should have the same value i.e. the
values in the binary search tree are distinct.

et
6) The value in any left sub-tree is less than the value of its parent node.
7) The value in any right sub-tree is greater than the value of its parent node.
8) The left and right sub-trees of each node are again binary search trees

Operations in Binary Search Tree:


Searching:
Searching a binary search tree for a specific key can be a recursive or an iterative
process. We begin by examining the root node. If the tree is null, the key we are searching for
does not exist in the tree.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Otherwise, if the key equals that of the root, the search is successful and we return the
node. If the key is less than that of the root, we search the left subtree. Similarly, if the key is
greater than that of the root, we search the right subtree.
This process is repeated until the key is found or the remaining subtree is null. If the
searched key is not found before a null subtree is reached, then the item must not be present in
the tree. This is easily expressed as a recursive
Algorithm:
function Find-recursive(key, node): // call initially with node = root
if node = Null or node.key = key then
return node
else if key < node.key then
return Find-recursive(key, node.left)
else

ww return Find-recursive(key, node.right)


The same algorithm can be implemented iteratively:

w.E function Find(key, root):


current-node := root

asy
while current-node is not Null do
if current-node.key = key then
return current-node

En
else if key < current-node.key then

gin
current-node := current-node.left
else

ee
current-node := current-node.right
return Null

rin
Because in the worst case this algorithm must search from the root of the tree to the
leaf farthest from the root, the search operation takes time proportional to the tree's height (see

g.n
tree terminology). On average, binary search trees with n nodes have O(log n) height.
However, in the worst case, binary search trees can have O(n) height, when the unbalanced
tree resembles a linked list (degenerate tree).

Insertion:
et
Insertion begins as a search would begin; if the key is not equal to that of the root, we
search the left or right subtrees as before. Eventually, we will reach an external node and add
the new key-value pair (here encoded as a record 'newNode') as its right or left child,
depending on the node's key. In other words, we examine the root and recursively insert the
new node to the left subtree if its key is less than that of the root, or the right subtree if its key
is greater than or equal to the root.
Here's how a typical binary search tree insertion might be performed in a binary tree
in C++:
void insert(Node*& root, int data)
{
if (!root)

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

root = new Node(data);


else if (data < root->data)
insert(root->left, data);
else if (data > root->data)
insert(root->right, data);
return;
}
To insert a new node in the tree, its key is first compared with that of the root. If its key
is less than the root's, it is then compared with the key of the root's left child. If its key is
greater, it is compared with the root's right child. This process continues, until the new node is
compared with a leaf node, and then it is added as this node's right or left child, depending on
its key.
There are other ways of inserting nodes into a binary tree, but this is the only way of

ww
inserting nodes at the leaves and at the same time preserving the BST structure.
Deletion:

w.E
Deletion of a node
When we delete a node, we need to consider how we take care of the children of the

asy
deleted node. This has to be done such that the property of the search tree is maintained.
Case 1: Node with no children
 If a node is a leaf node, it can be deleted immediately.
Case 2: Node with one child
En
gin
 It can be deleted by adjusting its parent pointer that points to its child node.
Case 3: Node has 2 children

ee
 Replace the data of the node to be deleted with its smallest data of the right subtree
and recursively delete that node.

rin
g.n
et
Deleting a node with two children from a binary search tree. First the rightmost node in
the left sub tree, the inorder predecessor 6, is identified. Its value is copied into the node being
deleted. The inorder predecessor can then be easily deleted because it has at most one child. The
same method works symmetrically using the inorder successor labeled 9.
Example:
Binary Search Tree for the input: 60, 25, 75, 15, 50, 66, 33, 44
60

25 75

Downloaded From : www.EasyEngineering.net


15 50 66
Downloaded From : www.EasyEngineering.net

Example:

To delete 25

ww 60 60

w.E 25 75 33 75

15 50 asy
66

En 15 50 66
33
gin 8

44
ee 44

rin
g.n
To delete 75

60 60

33 33
et
75 66

15 15
50 66 50

To delete
44 44 44
60
60

33 66 33 66

15 Downloaded From : www.EasyEngineering.net


50
Downloaded From : www.EasyEngineering.net

Algorithm to delete the nodes:


searchtree deletion (int x, searchtree T)
{
int t1;
searchtree temp;
if (T==NULL)
printf (“ Element not found”);

ww else if (x < T->element)


T->left = deletion (x, T->left);

w.E else if (x > T->element)

else
T->right = deletion (x, T->right);

{
asy
if (T->left && T->right)

En
{
T1 = findmin (T->right);

gin
T->element = t1;
T->right = deletion (T->element, T->right);
}
else
{
temp = T;
ee rin
g.n
if (T->left = NULL)
T=T->right;
else if (T->right == NULL)
T= T->left;
free (temp);
}
et
}
return T;

3. Explain the concept of graph traversal with example.


A graph G consist of a nonempty set V which is a set of nodes of the graph, a set E
which is the set of edges of the graph, and a mapping from the set for edge E to a set of pairs
of elements of V. It can also be represented as G= (V, E).

Depth-First Search:
A depth-first search (DFS) in an undirected graph G is like wandering in a labyrinth
with a string and a can of red paint without getting lost. We start at vertexs, tying the end of
our string to the point and painting s “visited”. Next we label s as our current vertex called u.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Now we travel along an arbitrary edge (u,v).


If edge (u,v) leads us to an already visited vertex v we return to u.If vertex v is
unvisited, we unroll our string and move to v, paint v “visited”, set v as our current vertex,
and repeat the previous steps.
Eventually, we will get to a point where all incident edges on u lead to visited vertices. We
then backtrack by unrolling our string to a previously visited vertex v. Then v becomes our
current vertex and we repeat the previous steps.
Then, if all incident edges on v lead to visited vertices, we backtrack as we did before.
We continue to backtrack along the path we have traveled, finding and exploring unexplored
edges, and repeating the procedure.
When we backtrack to vertex s and there are no more unexplored edges incident on s,
we have finished our DFS search.

ww
Algorithm DFS(v):
Input: A vertex v in a graph

w.E Output: A labeling of the edges as “discovery” edges and “backedges”


for each edge e incident on v do
if edge e is unexplored then

asy
let w be the other endpoint of e
if vertex w is unexplored then label e as a discovery edge

En
recursively call DFS(w) else
label e as a backedge

Example: gin
ee
 Depth-first traversal using an explicit stack.

rin
g.n
et

Sample Problem:

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Order of
A B C F E G D H I Stack
Traversal

ww The Preorder Depth First Tree:

w.E
asy
En
gin
ee
For a Graph G=(V, E) and n = |V| and m=|E|,
1) When Adjacency List is used, Complexity is O(m + n)

rin
2) When Adjacency Matrix is used, Complexity is O (n2). Because, Scanning each

g.n
row for checking the connectivity of a Vertex is in order O(n).

4. Explain the breadth-first Search technique with example.

et
Like DFS, a Breadth-First Search (BFS) traverses a connected component of a graph,
and in doing so defines a spanning tree with several useful properties. The starting vertex s
has level 0, and, as in DFS, defines that point as an “anchor.”
In the first round, the string is unrolled the length of one edge, and all of the edges
that are only one edge away from the anchor are visited. These edges are placed into level 1 .
In the second round, all the new edges that can be reached by unrolling the string 2
edges are visited and placed in level 2. This continues until every vertex has been assigned a
level. The label of any vertex v corresponds to the length of the shortest path from s to v.
Algorithm:
void BFS(Edge G[], int vertex, boolean Visited[])
{
Edge tmp;
int nextV;
Queue Q = new Queue();

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Q.enquque(new Integer(vertex));
while (!Q.empty())
{
nextV = ((Integer) Q.dequeue()).intValue();
if (!Visited[nextV])
{
Visited[next] = true;
for (tmp = G[nextV]; tmp != null; tmp = tmp.next)
{
Q.enqueue(new Integer(tmp.neighbor()));
}}}
}

ww
Example: Breadth-first traversal using a queue.

w.E
asy
En
gin
ee rin
Sample Problem:
g.n
et

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

BFS Tree: (The BFS-tree for undirected graph is a free tree)


A

B D E

C G

F H

ww Algorithm Analysis:

w.E For a Graph G=(V, E) and n = |V| and m=|E|,


1) When Adjacency List is used, Complexity is O(m + n).
2) When Adjacency Matrix is used, Complexity is O(n2). Because Scanning

asy
each row for checking the connectivity of a Vertex is in order O(n).

Important Questions:
En
gin
. 1. Consider the following binary tree:
G

D
/ \
B M
ee
/ \
T
\
X rin
/ \ / \
A C I K
\
Y g.n
\
P
a) What is the result of a post-order traversal of the above tree?
et (8)
b) What is the result of an in-order traversal of the above tree? (8)
2. Draw binary search tree for the following input list {60, 25, 75, 15, 50, 66, 33, 44}.
Trace the algorithm to delete the nodes {25, 75, 44} from the tree. (16)
3. Explain in detail, the in-order, pre-order, and post-order traversal techniques.
(8) [A/M–10]

4. Convert the expression ((A+B)*C-(D-E) ^ (F+G)) to equivalent prefix and postfix


notations. (8) [A/M–10]

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

5. Explain in detail, the different methods of traversing a binary tree with algorithm.
(8) [N/D–09]
6. What is binary search tree? Explain in detail, the various operations with an example.
(16)
7. Explain in detail, the various types of graph traversals with neat algorithms. (16)

ww
w.E
asy
En
gin
ee rin
g.n
et

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

DHANALAKSHMI COLLEGE OF ENGINEERING


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES
YEAR / SEM: II / 03 UNIT V
SORTING AND SEARCHING
PART A

1. What is sorting? How is sorting essential for database applications?


Sorting is the process of linear ordering of list of objects. Efficient sorting is important
to optimize the use of algorithms that require sorted lists to work correctly and for producing

ww
human-readable input.

2. What is meant by sorting?

w.E Sorting is any process of arranging items according to a certain sequence or in different
sets, and therefore, it has two common, yet distinct meanings:

sequence,
asy
1. Ordering: arranging items of the same kind, class or nature, in some ordered

2. Categorizing: grouping and labeling items with similar properties together (by sorts).

En
3. What are the factors to be considered while choosing a sorting technique?

gin
The factors to be considered while choosing a sorting technique are:
a) Time utilization
b) Memory utilization
ee rin
4. What are the two main classifications of sorting, based on the source of data?
The two main classifications of sorting based on the source of data are:
a) Internal sorting
g.n
b) External sorting

5. When is sorting method said to be stable? et


Sorting method is said to be stable when it maintains relative order of records with equal
keys.

6. What is meant by internal sorting?


An internal sort is any data sorting process that takes place entirely within the main
memory of a computer. This is possible whenever the data to be sorted is small enough to be
held in the main memory.
It takes place in the main memory of a computer.
Eg: Bubble sort, Insertion sort, Shell sort, Quick sort, Heap sort.

7. List out the internal sorting methods.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

The internal sorting methods are:


1) Bubble sort
2) Insertion sort
3) Shell sort
4) Quick sort
5) Heap sort

8. What is meant by external sorting?


External sorting is a term for a class of sorting algorithms that can handle massive
amounts of data. External sorting is required when the data being sorted do not fit into
the main memory (usually RAM) but must reside in the slower external memory (usually
a hard drive).

ww It takes place in the secondary memory of a computer.

9. List out the external sorting methods.

w.E The external sorting methods are:


1) Merge sort
2) Multiway merge
asy
3) Polyphase merge

En
10. Differentiate internal sorting from external sorting.

gin
Internal sorting External sorting

Computer.
ee
1. It takes place in the main memory of

rin
1. It takes place in the secondary memory
of a computer.
2. Eg: Bubble sort, Insertion sort, Shell sort,
Quick sort, Heap sort. g.n
2. Eg: Merge sort, Multiway merge,
Polyphase merge.

11. What is the running time of insertion sort if all keys are equal?
et
The running time of insertion sort is,
i. Worst case analysis : O( )
ii. Best case analysis : O(N)
iii. Average case of analysis : O( )

12. What is the main idea behind insertion sort?


It takes elements from the list one by one and inserts them in their current position into a
new sorted list. It consists of N-1 passes, where 'N' is the number of elements to be sorted.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

13. Why is the insertion sort most efficient when the original data is almost in the sorted
order?
The insertion sort is most efficient when the original data is almost in the sorted order
because the insertion sort may behave rather differently than if the data set originally contains
random data or is ordered in the reverse direction.

14. What is meant by insertion sort?


Insertion sort is a simple sorting algorithm: a comparison sort in which the sorted array
(or list) is built one entry at a time. It is much less efficient on large lists than more advanced
algorithms such as quick sort, heap sort, or merge sort.

15. What are the advantages of insertion sort?

ww The advantages of insertion sort are:


1) It is relatively efficient for small lists and mostly sorted lists.

w.E 2) Time efficient for small list.


16. What is meant by merge sort?
Merging is the process of combining two or more sorted files into a third sorted files. We

asy
can use this technique to sort a file in the following way:
1. Divide the file into n sub files of size 1, and merge adjacent (disjoint) pairs of files in

En
sorted in order. We can then have approximately n/2 files of size 2.

gin
2. Repeat this process until there is only one files remaining of size n.

ee
17. Write the merge sort algorithm and write its worst case, best case and average case
analysis. [N/D–09]
Algorithm: Merge Sort
rin
To sort the entire sequence A[1 .. n], make the initial call to the procedure MERGE-
SORT (A, 1, n).
MERGE-SORT (A, p, r) g.n
IF p < r
THEN q = FLOOR [(p + r)/2]
MERGE (A, p, q)
// Check for base case
// Divide step
// Conquer step.
et
MERGE (A, q + 1, r) // Conquer step.
MERGE (A, p, q, r) // Conquer step.
Algorithm analysis:
a) Worst case analysis: O(N log N)
b) Best case analysis: O(N log N)
c) Average case analysis: O(N log N)
18. What is the main idea behind quick sort?
Quick sort is a divide and conquer algorithm. Quick sort first divides a large list into two
smaller sub-lists: the low elements and the high elements. Quick sort can then recursively sort
the sub-lists.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

The steps are:


1. Pick an element called a pivot from the list.
2. Reorder the list so that all elements with values less than the pivot come before
the pivot, while all elements with values greater than the pivot come after it (equal values can
go either way). After this partitioning, the pivot is in its final position. This is called
the partition operation.
3. Recursively apply the above steps to the sub-list of elements with smaller values
and separately to the sub-list of elements with greater values.
The base case of the recursion is lists of size zero or one, which never need to be sorted.

19. Determine the average running time of quick sort. [N/D–09]


The average running time of quick sort is O (NlogN). The average case is when the

ww
pivot is the median of the array, and then the left and the right part will have the same size.
There are logN partitions and it needs N comparisons to obtain each partition (and not more
than N/2 swaps). Hence the complexity is O (NlogN)

w.E
20. Write the algorithm of quick sort. [M/J–10]
Algorithm: Quick sort

asy
void qsort(int A[],int left,int right)
{
int i,j,pivot,temp;
En
if(left<right)
{
gin
pivot=left;
i=left+1;
j=right;
ee rin
g.n
while(i<j)
{
while(A[pivot]>=A[i])
i=i+1;
while(A[pivot]<A[j])
j=j-1;
et
if(i<j)
{
temp=A[i]; //swap
A[i]=A[j]; //A[i]&A[j]
A[j]=temp;
}
}
temp=A[pivot] //swap A[pivot]&A[j]
A[pivot]=A[j]; A[j]=temp;
qsort(A,left,j-1);

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

qsort(A,j+1,right);
}}

21. What is meant by searching?


Searching is the process of finding a record in the table according to the given key value. It
is extensively used in data processing.

22. List out the types of searching.


The types of searching are:
1. Sequential search(Linear Search)
2. Indexed Sequential search
3. Binary Search

ww 4. Interpolation Search

w.E
23. Define – Linear search
Linear search or sequential search is defined as a method for finding a particular value in a
list that consists of checking every one of its elements, one at a time and in sequence, until the
desired one is found.
asy
Linear Search scans each entry in the table in a sequential manner until the desired record is
found.
Efficiency: O (n) En
gin
24. Define – Binary search ee rin
The most efficient method of searching a sequential table without the use of auxiliary

g.n
indices or tables is the binary search. Basically, the argument is compared with the key of the
middle element of the table. If they are equal the search ends successfully, otherwise either the
upper or lower half of the table must be searched.

PART B
et
25. What is external sorting? Explain with an example.

External sorting is a term for a class of sorting algorithms that can handle massive
amounts of data. External sorting is required when the data being sorted do not fit into the main
memory of a computing device (usually RAM) and instead they must reside in the
slower external memory (usually a hard drive). External sorting typically uses a hybrid sort-
merge strategy. In the sorting phase, chunks of data small enough to fit in main memory are
read, sorted, and written out to a temporary file. In the merge phase, the sorted sub files are
combined into a single larger file.
Example: Merge sort, Two way merge sort.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

MERGE SORT:
Merging is the process of combining two or more sorted files into a third sorted files. We
can use this technique to sort a file in the following way:
1. Divide the file into n sub files of size 1, and merge adjacent (disjoint) pairs of files in
sorted in order. We can then have approximately n/2 files of size 2.
2. Repeat this process until there is only one files remaining of size n
Merge sort is based on the divide-and-conquer paradigm. Its worst-case running time
has a lower order of growth than insertion sort. Since we are dealing with sub problems, we
state each sub problem as sorting a sub array A[p .. r]. Initially, p = 1 and r = n, but these values
change as we recurse through sub problems.
To sort A[p .. r]:

ww 1. Divide Step:
If a given array A has zero or one element, simply return; it is already sorted. Otherwise,

w.E
split A[p .. r] into two sub arrays A[p .. q] and A[q + 1 .. r], each containing about half of the
elements of A[p .. r]. That is, q is the halfway point of A[p .. r].

2. Conquer Step:
asy
Conquer by recursively sorting the two sub arrays A[p .. q] and A[q + 1 .. r].

3. Combine Step:
En
gin
Combine the elements back in A[p .. r] by merging the two sorted sub arrays A[p .. q]
and A[q + 1 .. r] into a sorted sequence. To accomplish this step, we will define a procedure

ee
MERGE (A, p, q, r). Note that the recursion bottoms out when the sub array has just one
element, so that it is trivially sorted.

rin
g.n
Algorithm: Merge Sort

et
To sort the entire sequence A[1 .. n], make the initial call to the procedure MERGE-
SORT (A, 1, n).
MERGE-SORT (A, p, r)
IF p < r // Check for base case
THEN q = FLOOR [(p + r)/2] // Divide step
MERGE (A, p, q) // Conquer step.
MERGE (A, q + 1, r) // Conquer step.
MERGE (A, p, q, r) // Conquer step.
Example: Bottom-up view of the above procedure for n = 8.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

ww
w.E
asy
Merging: What remains is the MERGE procedure. The following is the input and output of
the MERGE procedure.

En
INPUT: Array A and indices p, q, r such that p ≤ q ≤ r and subarray A[p .. q] is sorted

gin
and subarray A[q + 1 .. r] is sorted. By restrictions on p, q, r, neither subarray is empty.
OUTPUT: The two subarrays are merged into a single sorted subarray in A[p .. r].
We implement it so that it takes Θ(n) time, where n = r − p + 1, which is the number of
elements being merged.

Analysis:
ee rin
1. Worst case analysis: O(N log N)
2. Best case analysis: O(N log N) g.n
3. Average case analysis: O(N log N)
et
26. What is insertion sort? Explain with example.
Insertion sort is an efficient algorithm for sorting a small number of elements. Insertion
sort works the same way as one would sort a bridge or gin rummy hand, i.e. starting with an
empty left hand and the cards face down on the table. One card at a time is then removed from
the table and inserted into the correct position in the left hand.
To find the correct position for a card, it is compared with each of the cards already in
the hand, from right to left. The pseudo code for insertion sort is presented in a procedure called
INSERTION-SORT, which takes as a parameter an array A[1 . . n] containing a sequence of
length n that is to be sorted. (In the code, the number n of elements in A is denoted by length

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

[A]. The input numbers are sorted in place: the numbers are rearranged within the array A. The
input array A contains the sorted output sequence when INSERTION-SORT is finished.
Algorithm:
INSERTION-SORT (A)
for j <- 2 to length[A]
do key <- A[j]
Insert A[j] into the sorted sequence A[1 . . j - 1].
i <- j - 1
while i > 0 and A[i] > key
do A[i + 1] <- A[i]
i <- i - 1
A[i + 1] <- key

ww
Example:
The below example shows how this algorithm works for A = {5, 2, 4, 6, 1, 3}. The

w.E
index j indicates the "current card" being inserted into the hand. Array elements A [1.. j - 1]
constitute the currently sorted hand, and elements A[j + 1 . . n] correspond to the pile of cards still
on the table. The index j moves left to right through the array.

asy
At each iteration of the "outer" for loop, the element A[j] is picked out of the array (line 2).
Then, starting in position j - 1, elements are successively moved one position to the right until the

En
proper position for A[j] is found (lines 4-7), at which point it is inserted (line 8).

gin
ee rin
g.n
et
Time complexity of insertion sort:
In order to analyze insertion sort the INSERTION-SORT procedure is presented with the
time "cost" of each statement and the number of times each statement is executed. For each
j = 2, 3. . . n, where n =length[A], tj is the number of times the while loop test in line 5 is executed
for that value of j. It is assumed that comments are not executable statements, and as such they
take no time.
The running time of the algorithm is the sum of running times for each statement executed;
a statement that takes ci steps to execute and is executed n times will contribute ci n to the total

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

running time 3. To compute T(n), the running time of INSERTION-SORT, the products of the
cost and times columns are summed.
1) Worst case analysis : O( )
2) Best case analysis : O(N)
3) Average case of analysis : O( )

27. What is quick sort? Explain with example.


Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two
smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort
the sub-lists.
The steps are:
1. Pick an element, called a pivot, from the list

ww 2. Reorder the list so that all elements with values less than the pivot come before
the pivot, while all elements with values greater than the pivot come after it (equal values can

w.E
go either way). After this partitioning, the pivot is in its final position. This is called
the partition operation
3. Recursively apply the above steps to the sub-list of elements with smaller values

asy
and separately to the sub-list of elements with greater values
The base case of the recursion is lists of size zero or one, which never need to be sorted

Basic idea:
En
gin
1. Pick one element in the array, which will be the pivot.
2. Make one pass through the array, called a partition step, re-arranging the entries so that:

ee
a) The pivot is in its proper place

rin
b) Entries smaller than the pivot are to the left of the pivot
c) Entries larger than the pivot are to its right

g.n
3. Recursively apply quicksort to the part of the array that is to the left of the pivot,
and to the right part of the array.

et
Here we don't have the merge step, at the end all the elements are in the proper order.

Algorithm:
STEP1: Choosing the pivot - Choosing the pivot is an essential step. Depending on the
pivot the algorithm may run very fast, or in quadric time.
1. Some fixed element: e.g. the first, the last, the one in the middle. This is a bad
choice - the pivot may turn to be the smallest or the largest element,
then one of the partitions will be empty.
2. Randomly chosen (by random generator) - still a bad choice.
3. The median of the array (if the array has N numbers, the median is the [N/2]
largest number. This is difficult to compute - increases the complexity.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

4. The median-of-three choice: take the first, the last and the middle element.
Choose the median of these three elements.
Example:
8, 3, 25, 6, 10, 17, 1, 2, 18, 5
The first element is 8, the middle - 10, the last - 5. The median of [8, 10, 5] is 8

STEP 2: Partitioning - Partitioning is illustrated on the above example.


1. The first action is to get the pivot out of the way - swap it with the last element
5, 3, 25, 6, 10, 17, 1, 2, 18, 8
2. We want larger elements to go to the right and smaller elements to go to the
left. Two "fingers" are used to scan the elements from left to right and from
right to left:

ww [5, 3, 25, 6, 10, 17, 1, 2, 18, 8]


^
i
^
j

w.Ea) While i is to the left of j, we move i right, skipping all the elements
less than the pivot. If an element is found greater than the pivot, i stops

asy
b) While j is to the right of i, we move j left, skipping all the elements
greater than the pivot. If an element is found less than the pivot, j stops

En
c) When both i and j have stopped, the elements are swapped.
d) When i and j have crossed, no swap is performed, scanning stops,

gin
and the element pointed to by i is swapped with the pivot.
In the example the first swapping will be between 25 and 2, the second between 10
and 1.
3. Restore the pivot. ee rin
After restoring the pivot we obtain the following partitioning into three
groups:
[5, 3, 2, 6, 1] [ 8 ] [10, 25, 18, 17] g.n
et
STEP 3: Recursively quicksort the left and the right parts
Coding:
if( left + 10 <= right)
{
int i = left, j = right - 1;
for ( ; ; )
{
while (a[++i] < pivot ) {} // move the left finger

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

while (pivot < a[--j] ) {} // move the right finger

if (i < j) swap (a[i],a[j]); // swap


else break; // break if fingers have crossed
}
swap (a[I], a[right-1); // restore the pivot
quicksort ( a, left, i-1); // call quicksort for the left part
quicksort (a, i+1, right); // call quicksort for the left part
}
else insertionsort (a, left, right);
If the elements are less than 10, quicksort is not very efficient. Instead insertion sort is
used at the last phase of sorting.

ww
Analysis:
Worst-case: O (N2)

w.E This happens, when the pivot is the smallest (or the largest) element. Then one of the
partitions is empty, and we repeat recursively the procedure for N-1 elements.
Best-case O (NlogN)

asy
The best case is when the pivot is the median of the array,
and then the left and the right part will have same size. There are logN partitions, and to obtain

En
each partition we do N comparisons (and not more than N/2 swaps). Hence the complexity is O
(NlogN)
Average-case: O (NlogN)
Advantages: gin
ee
1) One of the fastest algorithms on average.

rin
2) Does not need additional memory (the sorting takes place in the array - this is called in-
place processing). Compare with merge sort: merge sort needs additional memory for
merging.
Disadvantages: The worst-case complexity is O (N2) g.n
28. What is linear search? Explain with example. et
In a linear search (sequential search) a target element is compared with each of the array
element starting from first element in the array up to the last element in the array or up to the
match found.

In this method, we start to search from the beginning of the list and examine each element
till the end of the list. If the desired element is found we stop the search and return the index of
that element. If the item is not found and the list is exhausted the search returns a zero value.
In the worst case the item is not found or the search item is the last (nth) element. For both
situations we must examine all n elements of the array so the order of magnitude or complexity
of the sequential search is n. i.e., O (n). The execution time for this algorithm is proportional to
n that is the algorithm executes in linear time.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

The algorithm for sequential search is as follows,


Algorithm : sequential search
Input : A, vector of n elements and k, search element
Output : j –index of k
Method: i=1
while (i<=n)
{
if(A[i]=k)
{
write("search successful")
write(k is at location i)
exit();

ww }
else

w.E i++
if end
while end

asy
write (search unsuccessful);
algorithm ends
Example:
En
gin The array we're searching
Lets search for the number 3. We start at the beginning and check the first element in the
array. Is it 3?
ee rin
Is the first value 3?
No, not it. Is it the next element?
g.n
Not there either. The next element?
Is the second value 3?
et
Is the third value 3?
Not there either. Next?

Is the fourth value 3? Yes! We found it.


In linear searching, we go through each element, in order, until we find the correct value.

Algorithm analysis:
The complexity of the search algorithm is given by the number C of comparisons between k
and array elements A[i].

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Best case: Clearly the best case occurs when k is the first element in the array A. i.e. k =
A[i] In this case, C(n) = 1.
Worst case: Clearly the worst case occurs when k is the last element in the array A or k
is not present in given array A (to ensure this we have to search entire array A till last element).
In this case, C(n) = n.
Average case: Here we assume that searched element k appear array A, and it is equally
likely to occur at any position in the array. Here the number of comparisons can be any of
numbers 1, 2, 3 … n, and each number occurs with the probability p = 1/n then,

ww i.e. C(n) = n
It means the average number of comparisons needed to find the location of k is

w.E
approximately equal to half the number of elements in array A. From above discussion, it may
be noted that the complexity of an algorithm in the average case is much more complicated to
analyze than that of worst case.

asy
Best case time complexity: Cbest = 1

En
Worst case time complexity: Cworst = n
Average case time complexity: Caverage = n

gin
29. What is binary search? Explain with example.

ee
A binary search or half-interval search algorithm finds the position of a specified input

rin
value (the search "key") within an array sorted by key value. In each step, the algorithm
compares the search key value with the key value of the middle element of the array.

g.n
If the keys match, then a matching element has been found and its index, or position, is

et
returned. Otherwise, if the search key is less than the middle element's key, then the algorithm
repeats its action on the sub-array to the left of the middle element or, if the search key is
greater, on the sub-array to the right. If the remaining array to be searched is empty, then the
key cannot be found in the array and a special "not found" indication is returned.
A binary search halves the number of items to check with each iteration, so locating an item
(or determining its absence) takes logarithmic time. The algorithm for binary search is given
below.
Algorithm:
Algorithm Bin search(a,n,x)
// Given an array a[1:n] of elements in non-decreasing
//order, n>=0,determine whether ‘x’ is present and
// if so, return ‘j’ such that x=a[j]; else return 0.
{
low:=1; high:=n;

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

while (low<=high) do
{
mid:=[(low+high)/2];
if (x<a[mid]) then high;
else if(x>a[mid]) then
low=mid+1;
else return mid;
}
return 0;
}
The above algorithm describes the binary search method. The while loop continues
processing as long as there are more elements left to check. At the conclusion of the procedure 0
is returned if x is not present, or ‘j’ is returned, such that a[j]=x.
We observe that low & high are integer Variables such that each time through the loop

ww
either x is found or low is increased by at least one or high is decreased at least one. Thus we
have 2 sequences of integers approaching each other and eventually low becomes > than high &
causes termination in a finite no. of steps if ‘x’ is not present.

w.E
Example:
1) Let us select the 14 entries.

asy
-15,-6,0,7,9,23,54,82,101,112,125,131,142,151.
 Place them in a[1:14], and simulate the steps Binsearch goes through as it

En
searches for different values of ‘x’.
 Only the variables, low, high & mid need to be traced as we simulate the
algorithm.
gin
 We try the following values for x: 151, -14 and 9 for 2 successful searches

X=151 low high mid


ee
& 1 unsuccessful search.

The below tables shows the traces of Bin search on these 3 steps.
rin
1
8
14
14
7
11 g.n
12
14
14
14
13
14 Found
et
x=-14 low high mid
1 14 7
1 6 3
1 2 1
2 2 2
2 1 Not found

x=9 low high mid


1 14 7
1 6 3
4 6 5 Found

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

Algorithm Binsearch(a,n,x) works correctly. We assume that all statements work as expected
and that comparisons such as x>a[mid] are appropriately carried out.
1. Initially low =1, high= n,n>=0, and a[1]<=a[2]<=……..<=a[n].
2. If n=0, the while loop is not entered and is returned.
3. Otherwise we observe that each time thro’ the loop the possible elements to be checked
of or equality with x and a[low], a[low+1],……..,a[mid],……a[high].
4. If x=a[mid], then the algorithm terminates successfully.
5. Otherwise, the range is narrowed by either increasing low to (mid+1) or decreasing high
to (mid-1).
6. Clearly, this narrowing of the range does not affect the outcome of the search.
7. If low becomes > than high, then ‘x’ is not present & hence the loop is exited.

Performance Analysis:

wwThe recurrence form of binary search is:

w.E T(n) = T(n/2)+1


1
when n>2
when n=1

asy
The time complexity of binary search is:

Best Case
(1) En Worst Case
(log n)
Average Case
(log n)

gin
Advantage of Binary Search algorithm:
The advantage is:
ee rin
1. Binary search is an optimal searching algorithm using which we can search the desired element
very efficiently.
Disadvantage of Binary Search algorithm:
The disadvantage is:
g.n
et
1. This algorithm requires the list to be sorted. Then only this algorithm is applicable.

Important Questions:
1. Explain in detail, the external sorting with an example. (16)
2. Explain in detail, the insertion sort with its time complexity. (16) [N/D–11]
3. Explain in detail, the merge sort with a suitable example. (16)
4. Explain in detail, the quick sort with an example. (16)
5. Explain in detail, the concept of linear search with suitable example. (16)
6. Explain in detail, the concept of binary search with suitable example. (16)

Downloaded From : www.EasyEngineering.net

You might also like