Ec6301 Dec
Ec6301 Dec
net
ww
w.E
a syE
ngi
nee
rin
g.n
et
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.
Data move openly around the system from Data is hidden and cannot be accessed by
function to function external functions
ww 5) Polymorphism
6) Dynamic binding
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.
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.
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
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
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.
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);
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;
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.
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
A myObject;
et
myObject.function();
}
void A::function()
{
cout<<"Hello World!";
}
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.
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.
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.
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:
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;
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.
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:
ww
37. Structure of C++ program:
It is of three types:
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 { }.
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).
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
ww {
int val1,val2;
public:
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.
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
ww {
………….// private members
public: must be public
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
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
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
-- - 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
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);
#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;
}
}
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.
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);
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();
}
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;
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>
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)
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
INHERITANCE
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)
2) Multiple inheritance
3) Hierarchical inheritance
4) Multilevel inheritance
5) Hybrid 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
};
C
Derived class
et
When a subclass inherits from a class that itself inherits from another class, it is known as
multilevel inheritance.
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
Sub class
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
Example:
class AB
{
public:
virtual void f() = 0;
};
ww variable or constant, you must declare a pointer before you can work with it. The general form of
a pointer variable declaration is:
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
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>
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();
}
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
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.
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
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
C Derived class
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
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:
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);
r.get_score(6.0);
return 0;
}
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);
ww }
// function body
w.E };
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
};
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;
{
// 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
UNIT III
LINEAR DATA STRUCTURES
PART A
ww
accessing functions.
2. List out the areas in which data structures are applied extensively.
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.
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.
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.
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.
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
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)
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.
ww
w.E dequeue
asy
(Deletion) Front Rear
En
gin
ee rin
g.n
et
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";
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()
{
cout<<"\n\n\n";
for(i=0;i<n;i++)
{
cout<<"\n\n\n"<<b[i];
}}
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
{
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;
}
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.
ww
w.E
Algorithm for Insertion at the End of Circular linked list:
{
asy
node* AddEnd(node* tail, int num)
}
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
After Deletion
ww
After Deletion
w.E
asy
En
gin
Deletion at the end of the Circular linked list
ee rin
g.n
et
After Deletion
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
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
while(ptr->next!=NULL)
/* Allocate memory for the new node and put data in it.*/
ptr = ptr->next;
ww
ptr->data = data;
ptr->next = NULL;
w.E
}
asy
En
gin
ee rin
Insertion Node in given location Linked List:
g.n
et
ww Deleting an element is similar to pop operation in Stack and Queue. A node can be deleted in
3 ways similar to Insertion.
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—
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.
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
{
return (stack[top--]);
}} item /
element
6
top 6 POP
operation
8 top 8
4
4
Stack
Stack
Application of Stack:
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.
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:
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();
}
}
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:
ww
rear :=rear+1;
q[rear]:=item;
end;
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
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]
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
ww trees T1, T2….Tk, each of which are connected by a directed edge from the root.
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.
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.
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.
ww pairs of elements of V.
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.
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.
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.
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.
26. What are the various operations of binary trees for link representation?
w.E
3) Visit the root
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.
32. Write an algorithm to find, insert and delete nodes in binary search tree.
ww if x NIL
then p[x] ← p[y]
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).
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
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.
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:
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
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
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)
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
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
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;
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.
ww
Algorithm DFS(v):
Input: A vertex v in a graph
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:
Order of
A B C F E G D H I Stack
Traversal
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).
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();
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
B D E
C G
F H
ww Algorithm Analysis:
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]
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
ww
human-readable input.
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
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( )
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.
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.
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);
qsort(A,j+1,right);
}}
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.
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.
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
[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
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( )
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.
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
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
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.
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?
Algorithm analysis:
The complexity of the search algorithm is given by the number C of comparisons between k
and array elements A[i].
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;
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
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
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:
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)