Upload
vdsrihari
View
222
Download
0
Embed Size (px)
Citation preview
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 1/63
REGULATION 2009 EC 2202 DATA STRUCTURES AND OBJECT ORIENTED
PROGRAMMING IN C++ 3 0 0 3
AIM
To provide an in-depth knowledge in problem solving techniques and data structures.
OBJECTIVES To learn the systematic way of solving problems
To understand the different methods of organizing large amounts of data
To learn to program in C++
To efficiently implement the different data structures
To efficiently implement solutions for specific problems
UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING 9
Introduction- Tokens-Expressions-contour Structures Functions in C++, classes and objects,
constructors and destructors ,operators overloading and type conversions .
UNIT II ADVANCED OBJECT ORIENTED PROGRAMMING 9
Inheritance, Extending classes, Pointers, Virtual functions and polymorphism, File Handling Templates
,Exception handling, Manipulating strings.
UNIT III DATA STRUCTURES & ALGORITHMS 9
Algorithm, Analysis, Lists, Stacks and queues, Priority queues-Binary Heap-Application, Heapshashing-
hash tables without linked lists
UNIT IV NONLINEAR DATA STRUCTURES 9
Trees-Binary trees, search tree ADT, AVL trees, Graph Algorithms-Topological sort, shortest path
algorithm network flow problems-minimum spanning tree - Introduction to NP - completeness.
UNIT V SORTING AND SEARCHING 9
Sorting Insertion sort, Shell sort, Heap sort, Merge sort, Quick sort, Indirect sorting, Bucket sort,
Introduction to Algorithm Design Techniques Greedy algorithm (Minimum Spanning Tree), Divide and
Conquer (Merge Sort), Dynamic Programming (All pairs Shortest Path Problem).
Total hours = 45
TEXT BOOKS:
1. Mark Allen Weiss, Data Structures and Algorithm Analysis in C, 3rd ed, Pearson Education Asia,
2007.
2. E. Balagurusamy, Object Oriented Programming with C++, McGraw Hill Company Ltd., 2007.
REFERENCES:
1. Michael T. Goodrich, Data Structures and Algorithm Analysis in C++, Wiley student edition, 2007.
2. Sahni, Data Structures Using C++, The McGraw-Hill, 2006.
3. Seymour, Data Structures, The McGraw-Hill, 2007.
4. Jean Paul Tremblay & Paul G.Sorenson, An Introduction to data structures with applications, Tata
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 2/63
McGraw Hill edition, II Edition, 2002.
5. John R.Hubbard, Schaums outline of theory and problem of data structure with C++, McGraw-Hill,
New Delhi, 2000.
6. Bjarne Stroustrup, The C++ Programming Language, Addison Wesley, 2000
7. Robert Lafore, Object oriented programming in C++, Galgotia Publication
UNIT I
PRINCIPLES OF OBJECT ORIENTED PROGRAMMING
Introduction- Tokens-Expressions-contour Structures Functions in C++, classes and objects,
constructors and destructors ,operators overloading and type conversions .
PART A
1. What is an identifier?
Identifiers are names for various programming elements in c++ program. such as variables, arrays,
function, structures, union, labels ect., An identifier can be Composed only of uppercase, lower case
letter, underscore and digits, but should start only with an alphabet or an underscore.
2. What is a keyword?
Keywords are word whose meanings have been already defined in the c compiler. They are also called as
reserved words.
(ex) main(), if, else, else, if, scanf, printf, switch, for, goto, while ect.,
3. Define constant in c++.
Constants in c++ refers to fixed values that do not change during execution of a program.
4. Define a variable.
A quantity ,Which may vary during execution of a program is called as a variable.
5. What are unary operators?
The operators that act upon a single operand are called as unary operators. The unary operators used in
c++ are - , ++, -- and sizeof operators.
6. What are binary operators?
The operators that act upon two operands are called binary operators. The binary operators used in c++
are +, -, *, / , %, =. etc.,
7. What are ternary operators?
The operators that act upon three operands are called as ternary operators. The ternary operator
available in c++ is (?:).This operator is also referred as conditional operator.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 3/63
8. What is meant by an expression?
An expression is a combination of constant, variable, operators and function calls written in any form as
per the syntax of the c++ language.
9. State the difference between c and c++.C C++
(i). Procedural programming language Object-oriented programming anguage
(ii) Global variable can be declared It is an error to declare a variable as global
(iii) Function prototypes are optional All functions must be prototyped.
(iv) Local variables can be declared only Local variables can be declared any where
the start of a c program in a c++ program.
(v) We can call a main() function, within This is not allowed
a program.
10. List the various oops concepts
Four main OOP concepts
Abstraction
creation of well-defined interface for an object, separate from its implementation
e.g., key functionalities (init, add, delete, count, print) which can be called independently of knowing
how an object is implemented
Encapsulation
keeping implementation details private i.e., inside the implementation hierarchy an object is defined
in terms of other objects Composition => larger objects out of smaller ones
Inheritance => properties of smaller objects are inherited by larger
objects
Polymorphism
use code transparently for all types of same class of object
i.e., morph one object into another object within same hierarchy
11. Define class and object
Class: It is defined as blueprint or it is a collection of objects
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 4/63
Objects: is an instance of a class
Almost like struct, the default privacy specification is private whereas with struct, the default privacy
specification is public
Example:
class point{
double x, y; // implicitly private
public:
void print();
void set( double u, double v );
};
12. Define inheritance
Inheritance
Objects are often defined in terms of hierarchical classes with a base class and one or more levels of
classes that inherit from the classes that are above it in the hierarchy.
For instance, graphics objects might be defined as follows:
Syntax for Inheritance
class derivedClass : public baseClass {
private :
// Declarations of additional members, if needed.
public:
// Declarations of additional members, if needed.
protected:
// Declarations of additional members, if needed.
}
13. Define encapsulation
Encapsulation is one of thr most important features of a class.It is the process os combining member
functions and the data it manipulates by logically binding the data ane keeping them safe from outside
interference.
14. Define abstraction.
Creation of well-defined interface for an object, separate from its implementation
e.g., key functionalities (init, add, delete, count, print) which can be called independently of knowing
how an object is implemented
15. Define polymorphism
Polymorphism means having many forms. It allows different objects to respond to the same message
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 5/63
in different ways, the response specific to the type of the object.
E.g. the message displayDetails() of the Person class should give different results when send to a Student
object (e.g. the enrolment number).
16. List out the benefits of oops.
Can create new programs faster because we can reuse code Easier to create new data types
Easier memory management
Programs should be less bug-prone, as it uses a stricter syntax and type checking.
`Data hiding', the usage of data by one program part while other program parts cannot access the data
Will whiten your teeth
19. List out the application of oops.
Client server computing
Simulation such as flight simulations.
Object-oriented database applications.
Artificial intelligence and expert system
Computer aided design and manufacturing systems.
Real time systems, such as process control, temperature control.
20. Define data hiding.
The purpose of the exception handling mechanism is to provide a means to detect and report an
exceptional circumstance so that appropriate action can be taken.
21. What is the use of scope resolution operator?
In C, the global version of the variable cannot be accessed from within the inner block. C++ resolves this
problem by introducing a new operator :: called the scope resolution operator. It is used to uncover a
hidden variable.
Syntax:
:: variable name
22. When will you make a function inline?
When the function definition is small, we can make that function an inline function and we can mainly
go for inline function to eliminate the cost of calls to small functions.
22. What is overloading?
Overloading refers to the use of the same thing for different purposes.
There are 2 types of overloading:
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 6/63
Function overloading
Operator overloading
23. What is the difference between normal function and a recursive function?
A recursive function is a function, which call it whereas a normal function does not.Recursive function cant be directly invoked by main function
24. What are objects? How are they created?
Objects are basic run-time entities in an object-oriented programming system. The class variables are
known as objects. Objects are created by using the syntax:
classname obj1,obj2,,objn;
(or) during definition of the class:
class classname
{
-------
-------
}obj1,obj2,,objn;
25. List some of the special properties of constructor function.
They should be declared in the public section.
They are invoked automatically when the objects are created.
They do not have return types, not even void and cannot return values.
Constructors cannot be virtual.
Like other C++ functions, they can have default arguments
26. Describe the importance of destructor.
A destructor destroys the objects that have been created by a constructor upon exit from the program
or block to release memory space for future use. It is a member function whose name is the same as the
class name but is preceded by a tilde.
Syntax:
~classname(){ }
27. Define modular programming.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 7/63
It is a process of splitting a large program in to smaller modules to perform the operations fast and,
which helps in easy error checking. Modules should be designed, implemented and documented with
regard to their possible future use in other projects.
28. What do you mean by friend functions?
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 thse classes. Such a function need not be a member of
any of these classes. Such common functions are called friend functions.
29. Mention the types of polymorphism.
The types of polymorphism are
? compile time polymorphism
? runtime polymorphism
30. What are member functions?
Functions that are declared within the class definition are referred as member function.
31. Define dynamic binding.
Dynamic binding means that the code associated with a given procedure call is not known until the time
of the call at run-time.
32. State the difference between a constructor and destructor.
Constructor Destructor
A constructor is used to initialize the object A destructor is used for releasing dynamically allocated
memory
No symbol precedes the class name A tilde symbol precedes the class name
Constructors can be overloaded Destructors cannot be overloaded
33. What is the use of new operator?
The new operator is used to allocate contiguous unnamed memory during execution time ane returns a
pointer to the start of it.
34. What is the use of static data member?
The static data member informs the compiler that only one copy of the data member exit and all objects
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 8/63
of the class should share that variable without duplicating it for each instance of the class.
35. What is the different between a pre-increment and post-increment operator.
A pre-increment operation such as ++a, increments the value of a by 1,before a is used for computation,
while a post-increment operation such as a++, uses the current value or present value of a in thecalculation and then increments the value of a by 1.
36. Distinguish between break and continue statement.
Break continue
a) Used to terminate the loops or to Used to transfer the control to the
Exit loop from a switch. Start of loop
b) The break statement when executed The continue statement when
causes Immediate termination of loop executed caused immediate
containing it. termination of the current iteration of the loop.
37. Distinguish between while and do-while loop.
While loop do-while loop
a) The while loop tests the condition The do-while loop tests the condition
before each iteration after the first iteration
b) If the condition fails initially the loop Even if the condition fails initially
Is skipped entirely even in the first the loop is executed once
Iteration.
PART B (16 MARK)
1. State the merits and demerits of object oriented methodology.
Merits:
Can create new programs faster because we can reuse code
Easier to create new data types
Easier memory management
Programs should be less bug-prone, as it uses a stricter syntax and type checking.
`Data hiding', the usage of data by one program part while other program parts cannot access the data
Will whiten your teeth
Demerits:
disadvantages of C++ over Java:
Java protects you from making mistakes that C/C++ dont, as youve
C++ has many concepts and possibilities so it has a steep learning curve
extensive use of operator overloading, function overloading and virtual
functions can very quickly make C++ programs very complicated
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 9/63
shortcuts offered in C++ can often make it completely unreadable, just like in C
2. Explain the basic concepts of object oriented programming in detail with example.
BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
These include:
? Objects? Classes
? Data abstraction and encapsulation
? Inheritance
? Polymorphism
? Dynamic binding
? Message passing
Objects:
Objects are the basic run-time entities in an object oriented programming. They may represent a
person, a place, a bank account or any item that the program has to handle. They may represent user-
defined data such as vectors, time and lists. Programming problem is analyzed in terms of objects and
the nature of communication b/n them.
When a program is executed, the objects interact by sending messages to another. Each object contains
data and code to manipulate the data. Objects can interact without having to know the details of each
others data or code. It is sufficient to know the type of message
accepted, and the type of message accepted and the type of response returned by the objects.
Classes:
The entire set of data and code of an object can made a user defined data type with the help of a class.
In fact the objects are variable of the type class. Once class has been defined we can create any number
of objects belonging to that class. In short, a class serves as a blueprint or a plan or a template. It
specifies what data and what functions will be included in objects of that class. Defining the class
doesnt create any objects, just as the mere existence of a type int doesnt create any variables.
Data Abstraction and Encapsulation:
The wrapping up of data and functions into a single unit is known as encapsulation. It is the most striking
feature of the class. The data is not accessible to the outside world and only those functions which are
wrapped in the class can access it. These functions provide interface b/n the objects data and the
program. This insulation of the data from direct access by the program is called data hiding or
information hiding.
Abstraction represents the act of representing the essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost and functions to operate on these attributes. The attributes are
called data members and functions are called member functions or methods.
Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).
Inheritance:
It is the process by which objects of one class acquire the properties of objects of another class. It
supports the concept of hierarchical classification. For example, the bird robin is a part of the class
flying bird which is again a part of the class bird.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 10/63
This concept provides the idea of reusability. This means that we can add additional features to an
existing class without modifying it. This is possible by a deriving a new class from an existing one. The
new class will have the combined features of both the classes.
Polymorphism:
It means the ability to take more than one form. An operation may exhibit different behavior in different
instances. The behavior depends upon the types of data used in the operation. For example the
operation addition will generate sum if the operands are numbers whereas if the operands are strings
then the operation would produce a third string by concatenation. The process of making an operator to
exhibit different behaviors in different instances is known as operator overloading.
A single function name can be used to handle different types of tasks based on the number and types of
arguments. This is known as function overloading.
It allows objects to have different internal structures to share the same external interface.
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic Binding (late binding) means the code associated with the given procedure call is not known
until the time of the call at run-time. It is associated with the polymorphism and inheritance.
Message Passing:
The process of programming in OOP involves the following basic steps:
? Creating classes that define objects and their behavior
? Creating objects from class definitions
? Establishing communication among objects
A message for an object is request for execution of a procedure and therefore will invoke a function
(procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function (message) and the
information to be sent.
E.g.: employee.salary(name);
Object: employee
Message: salary
Information: name
3. State the rules to be followed while overloading an operator.write a program to illustrate overloading.
OPERATOR OVERLOADING:
Operator overloading means giving additional meaning to existing operators
By operator overloading an existing operator can be made to perform different operations than the
stipulated one.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 11/63
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 12/63
}
void show()
{
cout <<"\n The value of the object is\n"<<a;
}void operator - ()
{
a=-a;
}
};
void main()
{
clrscr();
unary u;
u.get();
u.show();
-u; //unary operator - called
u.show();
getch();
}
O/P:
The value of the object is
10
The value of the object is
-10
In the above program, the unary operator minus is overloaded.
In this an object u is created and given the value 10
When the unary operator is called the operator function is invoked and the value of the member
data of the object u is negated.
The negated value is then displayed.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 13/63
4. (i)Describe the application of oop technology
Applications of OOP:
? Real time systems? Simulation and modeling
? AI and expert systems
? Neural networks and parallel programming.
Decision support and office automation systems
(ii)What is an inline function?
INLINE FUNCTIONS :
An inline function is a function that is expanded in line when it is invoked. That is , the complier replaces
the function call with the corresponding function code.The inline function are defined as follows:
inline function header
{
function body
}
Example :
inline int cube(int a)
{
return (a*a*a);
}
Program :
#include
inline float mul(float x, float y)
{
return (x*y);
}
inline float div(double p, double q)
{
return( p / q )
}
int main()
{
float a=12.35;
float b=9.32;
cout<< mul(a,b);
cout<<div(a,b);
return 0;
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 14/63
}
5. (i).Explain copy constructor with suitable c++ coding.
Constructor:
A constructor is a special member function whose task is to initialize the objects of its class. It is specialbecause its name is the same as the class name. The constructor is invoked whenever an object of its
associated class its created.
A constructor is declared and defined as follows:
class sample
{
int m,n;
public:
sample()
{
m = n = 0;
}
// some code
};
void main()
{
sample s; // object is created
// some code
}
During the object creation, it also initializes the data members m and n to 0.
Default Constructor:
A constructor that accepts no parameters is called the default constructor.
Characteristics of a constructor:
? They should be declared in the public section
? They are invoked automatically when the objects are created
? They do not have return types
? They cannot be inherited
? They can have default arguments
? It cannot be virtual
? We cannot refer to their addresses
? An object with a constructor or destructor can not be used as a member of a union
? They make implicit calls to the operators new and delete when memory allocation is required
Copy constructor:
A copy constructor takes a reference to an object of the same class as itself as an argument.
Example:
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 15/63
It sets the value of every data element of s3 to the value of the corresponding data element of s2
Constructors with default arguments:
It is possible to define constructors with default arguments.
Example:
Inside the class definition:sample(int a, int b = 10)
Inside the main():
sample s2(20);
assigns 20 to x and 10 to y.
where as
sample s5(25,35) ; assigns 25 to x and 35 to y
(ii).List out the rules for overloading operator.
OPERATOR OVERLOADING:
Operator overloading means giving additional meaning to existing operators
By operator overloading an existing operator can be made to perform different operations than the
stipulated one.
It doesnt change the meaning and precedence of the original operator.
Almost all the operators in c++ can be overloaded except the following
o Sizeof ()
o Conditional operator (?:)
o Scope resolution operator (::)
o Class member access operator (.,.*)
SYNTAX:
Return-type operator op-symbol(argument list)
{
body of the function;
}
Generally there are three general classifications of operator namely
Operator
Unary binary ternary
Among the above unary and binary operators can be overloaded and ternary operator cannot be
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 16/63
overloaded.
6. Compare and contrast the following control structure with example:
(i). break statement & continue statement.
Break continue
a) Used to terminate the loops or to Used to transfer the control to the
Exit loop from a switch. Start of loop
b) The break statement when executed The continue statement when
causes Immediate termination of loop executed caused immediate
containing it. termination of the current iteration of the loop.
(ii). Do while and the while statement.
While loop do-while loop
c) The while loop tests the condition The do-while loop tests the condition
before each iteration after the first iteration
d) If the condition fails initially the loop Even if the condition fails initially
Is skipped entirely even in the first the loop is executed once
Iteration.
UNIT II
ADVANCED OBJECT ORIENTED PROGRAMMING
Inheritance, Extending classes, Pointers, Virtual functions and polymorphism, File Handling Templates,
Exception handling, Manipulating strings.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 17/63
PART A
1. What are the c++ operators that cannot be overloaded?
? Size operator (sizeof)
? Scope resolution operator (::)? Class member access operators(. , .*)
? Conditional operator (?:)
2. What is a virtual base class?
When a class is declared as virtual c++ takes care to see that only copy of that class is inherited,
regardless of how many inheritance paths exist between the virtual base class and a derived class.
3. What is the difference between base class and derived class?
The biggest difference between the base class and the derived class is that the derived class contains the
data members of both the base and its own data members. The other difference is based on the
visibility modes of the data members.
4. What are the rules governing the declaration of a class of multiple inheritance?
More than one class name should be specified after the : symbol.
Visibility modes must be taken care of.
If several inheritance paths are employed for a single derived class the base class must be appropriately
declared
5. Mention the types of inheritance.
Single inheritance.
2. Multiple inheritance.
3. Hierarchical inheritance.
4. Multilevel inheritance.
5. Hybrid inheritance.
6. Define dynamic binding.
Dynamic binding means that the code associated with a given procedure call is not known until the time
of the call at run-time.
7. What do u mean by pure virtual functions?
A pure virtual function is a function declared in a base class that has no definition relative to the base
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 18/63
class. In such cases, the compiler requires each derived class to either define the function or redeclare it
as a pure virtual function. A class containing pure virtual functions cannot be used to declare any objects
of its own.
8. What are templates?
Templates enable us to define generic classes. A template can be considered as a kind of macro. When
an object of a specific type is defined for actual use, the template definition for that class is substituted
with the required data type. Since a template is defined with a parameter that would be replaced by the
specific data type at the time of actual use of the class or function, the templates are sometimes called
parameterized classes or functions
9. What is exception handling?
The purpose of the exception handling mechanism is to provide a means to detect and report an
exceptional circumstance so that appropriate action can be taken.
10. Give the general format of class template.
The general format of a class template is:
template
class classname
{
//
//class member specification
//with anonymous type T
//wherever appropriate
//
};
11. Can we overlaod template function if so explain how.
Yes, a template function can be overloaded either by template functions or ordinary functions of its
name. in such cases, the overloading resolution is accomplished as follows:
1) Call an ordinary function that has an exact match.
2) Call a template function that could be created with an exact match.
3) Try normal overloading resolution to ordinary functions and call the one that matches.
12. List the kinds of exception.
Exceptions are of two kinds namely
Synchronous exceptions
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 19/63
Asynchronous exceptions
13. What are the errors in synchronous type exceptions?
Errors such as out-of-range index and over-flow belong to the synchronous type exceptions.
14. What are the errors in asynchronous type exceptions?
The errors that ware caused by errors beyond the control of the program (such as keyboard interrupts)
are called asynchronous exceptions.
15. What are the tasks that are performed by the error handling mechanism?
The mechanism suggests a separate error handling code that performs the following tasks:
1) Find the problem (Hit the exception).
2) Inform that an error has occurred (Throw the exception).
3) Receive the error information (Catch the exception).
4) Take corrective actions (Handle the exception).
16. Mention the key words used in exception handling.
The keywords used in exception handling are
throw
try
catch
17. Give the syntax of exception handling mechanism.
The syntax of exception handling mechanism is as follows:
try
{
---------------------
throw exception
---------------------
}
catch(type arguments)
{
---------------------
---------------------
}
----------------------
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 20/63
----------------------
18. List the ios format function.
The ios format functions are as follows:
width() precision()
fill()
setf()
unsetf()
19. List the manipulators.
The manipulators are:
setw()
setprecision()
setfill()
setiosflags()
resetiosflags()
20. Mention the equicalent ios function for manipulators.
Manipulator Equivalent ios function
setw(int w) width()
setprecision(int d) precision()
setfill(int c) fill()
setiosflags(long f) setf()
resetiosflags(long f) unsetf()
endl \n
21. Define fill functions.
The fill( ) function can be used to fill the unused positions of the field by any desired character rather
than by white spaces (by default). It is used in the following form:
cout.fill(ch);
where ch represents the character which is used for fi lling the unused positions. For example, the
statements
cout.fill(*);
cout.width(10);
cout<<5250<<\n;
will produce the following output:
PART B
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 21/63
1. Explain hybrid inheritance with suitable C++ coding.
2. Explain multiple inheritances with suitable c++ coding.
INHERITANCE:
Inheritance is a mechanism of deriving a new class from a old class.
It provides the concept of reusability By inheritance some or all the properties of a class can be derived in to another class.
The class which provides the properties is called as base class and the class which derives the
properties is called as derived class.
Multiple inheritance:
It is a type of inheritance in which a class can inherit properties from more than one class.
Syntax:
Class derivedclass name : visibility mode baseclass1,visibilitmode baseclass2
{
body of the derived class;
};
visibility mode can be either private or public.
Example :
#include
#include
class bc1
{
protected:
int a;
public :
void get()
{
cout <<\n enter the value for a\n;
cin >>a;
}
};
class bc2
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 22/63
{
protected:
int b;
public;
void get1()
{cout << \n enter the value for b \n;
cin>>b;
}
};
class dc : public bc1, public bc2
{
public :
void show()
{
cout <<The values of a and b are ;
cout <<a<<\n<<b;
}
};
void main()
{
clrscr();
dc d;
d.get();
d.get1();
d.show();
}
3. Define polymorphism. Explain the different types of polymorphism.
Polymorphism
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 23/63
Run time compile time
Or or
Dynamic binding static binding
Or or
late binding early binding
Virtual fuctions operator overloading function overloading
Linking a function call to the function definition is called as binding.
If the binding is done at compile time then it is called as compile time polymorphism.
Compile time polymorphism is achieved by using function overloading and operator overloading.
If the binding is done at run time then it is called as run time polymorphism. It is achieved by using
virtual functions.
VIRTUAL FUNCTIONS:
When the same function is used in both the base class and derived class and if a pointer of base class is
used to access the members of the derived class , then the members appropriate to the base class is
called.
Example:
#include
#include
class base
{
public:
void show()
{
cout <<\n This is a base class\n;
}
};
class derived : public base
{
public:
void show()
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 24/63
{
cout <<\n This is a derived class\n;
}
};
void main(){
base b,*bptr;
bptr=&b;
bptr->show();
derived d;
bptr=&d;
bptr->show();
getch();
}
o/p
This is a base class
This is a base class
This can be overcome by using virtual functions.
The base class member functions should be preceeded by a keyword virtual.
Example:
#include
#include
class base
{
public:
virtual void show()
{
cout <<\n This is a base class\n;
}
};
class derived : public base
{
public:
void show()
{
cout <<\n This is a derived class\n;
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 25/63
}
};
void main()
{
base b,*bptr;bptr=&b;
bptr->show();
derived d;
bptr=&d;
bptr->show();
getch();
}
o/p
This is a base class
This is a derived class
4. Explain multiple catch statement with help of suitable C++ coding.
EXCEPTION HANDLING
Exceptions are run time anomalies or unusual conditions that a program may encounter while
executing. Anomalies might include conditions such as division by zero, access to an array outside of its
bounds, or running out of memory or disk space. When a program encounters an exceptional condition,
it is important that it is identified and dealt with effectively.
Exceptions are of two kinds, namely, synchronous exceptions and asynchronous exceptions. Errors such
as out-of-range index and over flow belong to the synchronous exceptions. The errors that are
caused by events beyond the control of the program are called asynchronous exceptions. The proposed
exception handling mechanism is designed to handle only synchronous exceptions. The mechanism
performs following tasks:
? Find the problem (Hit the exception).
? Inform that an error has occurred (Throw the exception).
? Receive the error information (Catch the expression).
? Take corrective actions (Handle the exceptions).
The error handling code basically consists of two segments one to detect errors and to throw
exceptions, and other to catch the exceptions and to take appropriate actions.
Exception Handling Mechanism:
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 26/63
It is built upon three keywords, namely, try, throw and catch.
The keyword try is used to preface a block of statements which may generate exceptions. This block of
statements is known as try block.
When an exception is detected, it is thrown using a throw statement in the try block.
A catch block is defined by the keyword catch catches the exception thrown by the throw statement
in the try block, and handles it appropriately. If the type of object thrown matches the arg type in thecatch statement, then catch block is executed for handling the exception.
If they do not match the program is aborted with the help of the abort() function is invoked by default.
When no exception is detected and thrown, the control goes to the statement immediately after the
catch block.
Most often exceptions are thrown by the functions that are invoked from within the try blocks. The
point at which the throw is executed is called the throw point.
The general format of code for this kind of relationship is shown below
Multiple catch statements:
It is possible that a program segment has more than one condition to throw an exception. In such cases,
we can associate more than one catch statement with a try as shown below:
try
{ // try block
}
catch(type1 arg)
{ // catch block1 }
catch(type2 arg)
{ // catch block2 }
catch(typeN arg)
{ // catch blockN }
Catch All Exceptions:
In some situations we may not be able to anticipate all possible types of exceptions we can force a catch
statement to catch all exceptions instead of a certain type alone. This is achieved as follows:
catch ()
{
// statement of processing all exceptions
}
5. Describe the various file modes and its syntax.
FILE
To handle large volumes of data, we need to use some devices such as floppy disk or hard disk to store
the data. The data is stored in these devices using the concept of files. A file is a collection of related
data stores in a particular area on the disk. Programs can be designed to perform the read and write
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 27/63
operations on these files.
A program involves either or both of the following kinds of data communication:
1. Data transfer between the console unit and the program.
2. Data transfer between the program and a disk file.
The I/O system of C++ uses file stream as an interface b/n the programs and the files.
The stream that supplies data to the program is known as input stream. The stream that receives datafrom the program is known as output stream. In other words, the input stream reads data from the file
and the output stream writes data to the file.
Classes for File Stream Operations:
The I/O system of C++ contains a set of classes that define the file handling methods. These include
ifstream, ofstream and fstream. These classes are contained in the header file fstream. This file should
be included for performing file operations.
The filename is a string of characters that make up a valid filename for the operating system. It may
contain two parts, a primary name and an optional period with extension.
Examples:
Input.txt
Student
For opening a file, we must create a file stream and then link it to the filename. There are two ways of
opening a file:
? Using the constructor function of the class.
? Using the member function open() of the class.
The first method is useful when only one file in the stream is used. The second method is useful when
multiple files are managed using one stream.
File Modes:
The two methods that we discussed can also take two arguments instead of one. The second argument
will specify the file-mode. The general form of the function open() with two arguments is:
stream-object.open (filename, mode);
Parameter Meaning
ios::app Append to end of file
ios::ate Go to end of file on opening
ios::binary Binary file
ios::in Open file for reading only
ios::nocreate Open fails if the file does not exist
ios::noreplace Open fails if the file already exists
ios::out Open file for writing only
ios::trunc Delete the contents of the file if it exists
File pointers and their manipulations:
Each file has two associated pointers known as the file pointers. They are input pointer and output
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 28/63
pointer. The input pointer is used for reading the contents of a given file location and the output pointer
is used for writing to a given file location.
Read only mode:
Input pointer is automatically set at the beginning so that we can read the file from start.
Write only mode:
Existing contents are deleted and the output pointer is set at the beginning.Append mode:
The output pointer is set to the end of file.
Functions for manipulations of file pointers:
seekg() Moves input pointer to a specified location
seekp() Moves output pointer to a specified location
tellg() Gives the current position of the input pointer
tellp() Gives the current position of the output pointer
Example:
infile.seekg(10);
moves file pointer to the byte number 10. The bytes are numbered from zero hence it points to the 11th
byte in the file.
ofstream out
out.open(filename,ios::app);
int p = out.tellp();
The above program will give the number of bytes in the file, since the file is opened in the append mode.
6. Discuss the need for exception with try, catch and throw keywords.
Exceptions are run time anomalies or unusual conditions that a program may encounter while
executing. Anomalies might include conditions such as division by zero, access to an array outside of its
bounds, or running out of memory or disk space. When a program encounters an exceptional condition,
it is important that it is identified and dealt with effectively.
Exceptions are of two kinds, namely, synchronous exceptions and asynchronous exceptions. Errors such
as out-of-range index and over flow belong to the synchronous exceptions. The errors that are
caused by events beyond the control of the program are called asynchronous exceptions. The proposed
exception handling mechanism is designed to handle only synchronous exceptions. The mechanism
performs following tasks:
? Find the problem (Hit the exception).
? Inform that an error has occurred (Throw the exception).
? Receive the error information (Catch the expression).
? Take corrective actions (Handle the exceptions).
The error handling code basically consists of two segments one to detect errors and to throw
exceptions, and other to catch the exceptions and to take appropriate actions.
Exception Handling Mechanism:
It is built upon three keywords, namely, try, throw and catch.
The keyword try is used to preface a block of statements which may generate exceptions. This block of
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 29/63
statements is known as try block.
When an exception is detected, it is thrown using a throw statement in the try block.
A catch block is defined by the keyword catch catches the exception thrown by the throw statement
in the try block, and handles it appropriately. If the type of object thrown matches the arg type in thecatch statement, then catch block is executed for handling the exception.
If they do not match the program is aborted with the help of the abort() function is invoked by default.
When no exception is detected and thrown, the control goes to the statement immediately after the
catch block.
Most often exceptions are thrown by the functions that are invoked from within the try blocks. The
point at which the throw is executed is called the throw point.
The general format of code for this kind of relationship is shown below:
Example:
#include
void divide(int a, int b)
{
if(b!=0)
cout << Result = << a/b;
else
throw(b);
}
void main()
{
cout << Enter two numbers ;
int x,y;
cin >> x >> y;
try
{
divide(x,y);
}
catch(int i)
{
cout << Error! Dividing by Zero ;
}
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 30/63
7. Explain the various forms of inheritance in C++ with necessary coding.
INHERITANCE:
Inheritance is a mechanism of deriving a new class from a old class.
It provides the concept of reusability
By inheritance some or all the properties of a class can be derived in to another class. The class which provides the properties is called as base class and the class which derives the
properties is called as derived class.
Types:
There are five types of inheritance viz
1. Single level inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hybrid inheritance and
5. Hierarchical inheritance
Multiple inheritance:
It is a type of inheritance in which a class can inherit properties from more than one class.
Syntax:
Class derivedclass name : visibility mode baseclass1,visibilitmode baseclass2
{
body of the derived class;
};
visibility mode can be either private or public.
diagram:
refer diagram at pg 193 in E. Balaguruswamy.
Example :
#include
#include
class bc1
{
protected:
int a;
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 31/63
public :
void get()
{
cout <<\n enter the value for a\n;
cin >>a;
}};
class bc2
{
protected:
int b;
public;
void get1()
{
cout << \n enter the value for b \n;
cin>>b;
}
};
class dc : public bc1, public bc2
{
public :
void show()
{
cout <<The values of a and b are ;
cout <<a<<\n<<b;
}
};
void main()
{
clrscr();
dc d;
d.get();
d.get1();
d.show();
}
output:
Enter the value for a
20
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 32/63
Enter the value for b
30
The values of a and b are
20
30
.
UNIT III
DATA STRUCTURES & ALGORITHMS
Algorithm, Analysis, Lists, Stacks and queues, Priority queues-Binary Heap-Application, Heapshashing-
hash tables without linked lists
1. Write down the definition of data structures?
A data structure is a mathematical or logical way of organizing data in the memory that consider not
only the items stored but also the relationship to each other and also it is characterized by accessing
functions.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 33/63
2. Give few examples for data structures?
Stacks, Queue, Linked list, Trees, graphs
3. Define Algorithm?
Algorithm is a solution to a problem independent of programming language. It consist of set of finite
steps which, when carried out for a given set of inputs, produce the corresponding output and terminate
in a finite time.
4. What are the features of an efficient algorithm?
Free of ambiguity
Efficient in execution time
Concise and compact
Completeness
Definiteness
Finiteness
5. List down any four applications of data structures?
Compiler design
Operating System
Database Management system
Network analysis
6. What is meant by an abstract data type (ADT)?
An ADT is a set of operation. A useful tool for specifying the logical properties of a datatype is the
abstract data type.ADT refers to the basic mathematical concept that defines the datatype.
Eg.Objects such as list, set and graph along their operations can be viewed as ADT's.
7. What are the operations of ADT?
Union, Intersection, size, complement and find are the various operations of ADT.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 34/63
8. What is meant by list ADT?
List ADT is a sequential storage structure. General list of the form a1, a2, a3.., an and the size of the list
is 'n'. Any element in the list at the position I is defined to be ai, ai+1 the successor of ai and ai-1 is the
predecessor of ai.
9. What are the various operations done under l ist ADT?
Print list
Insert
Make empty
Remove
Next
Previous
Find kth
10.What is a Rational number?
A Rational number is a number that can be expressed as the quotient of two integers. Operations on
Rational number:
Creation of rational number from two integers.
Addition
Multiplication
Testing for equality.
11. What are the two parts of ADT?
Value definition
Operator definition
12. What is a Sequence?
A sequence is simply an ordered set of elements.A sequence S is sometimes written as the enumeration
of its elements,such as
S =
If S contains n elements,then length of S is n.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 35/63
13. Define len(S),first(S),last(S),nilseq ?
len(S) is the length of the sequence S.
first(S) returns the value of the first element of S
last(S) returns the value of the last element of Snilseq :Sequence of length 0 is nilseq .ie., contains no element.
14. What are the four basic data types?
int,float,char and double
15. What are the two things specified in declaration of variables in C?
It specifies the amount of storage that must be set aside for objects declared with
that type.
How data represented by strings of bits are to be interpreted.
16. What is a pointer?
Pointer is a variable, which stores the address of the next element in the list. Pointer is basically a
number.
17. What is an array ?
Array may be defined abstractly as a finite ordered set of homogenous elements.Finite means there is a
specific number of elements in the array.
18. What are the two basic operations that access an array?
Extraction:
Extraction operation is a function that accepts an array, a ,an index,i,and
returns an element of the array.
Storing:
Storing operation accepts an array , a ,an index i , and an element x.
19. Define Structure?
A Structure is a group of items in which each item is identified by its own identifier ,each of which is
known as a member of the structure.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 36/63
20. Define Union ?
Union is collection of Structures ,which permits a variable to be interpreted in several different ways.
21. Define Automatic and External variables?
Automatic variables are variables that are allocated storage when the function is invoked.
External variables are variables that are declared outside any function and are allocated storage at the
point at which they are first encountered for the remeinder of the programs execution.
22. Define Recursion?
Recursion is a function calling itself again and again.
23. What is a Fibonacci sequence?
Fibonacci sequence is the number of integers
0,1,1,2,3,5,8,13,21,34,.
Each element in this sequence is the sum of the two preceding elements.
24. What is a Stack?
A Stack is 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 list.
23. What are the two operations of Stack?
_ PUSH
_ POP
24. Write postfix from of the expression A+B-C+D?
A-B+C-D+
25. What is a Queue?
A Queue is an ordered collection of items from which items may be deleted at
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 37/63
one end called the front of the queue and into which tems may be inserted at
the other end called rear of the queue.Queue is called as Firstin-First-
Out(FIFO).
26. What is a Priority Queue?
Priority queue is a data structure in which the intrinsic ordering of the elements does determine the
results of its basic operations. Ascending and Descending priority queue are the two types of Priority
queue.
27. What are the different ways to implement list?
Simple array implementation of list
Linked list implementation of list
28. What are the advantages in the array implementation of list?
a) Print list operation can be carried out at the linear time
b) Find Kth operation takes a constant time
29. What is a linked list?
Linked list is a kind of series of data structures, which are not necessarily adjacent in memory. Each
structure contain the element and a pointer to a record containing its successor.
30.Name the two fields of Linked list?
Info field
Next field
31. What is a doubly 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.
32.Name the three fields of Doubly Linked list?
Info field
Left field
Right field
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 38/63
33. Define double circularly linked list?
In a doubly linked list, if the last node or pointer of the list, point to the first element of the list,then it is
a circularly linked list.
34. What is the need for the header?
Header of the linked list is the first element in the list and it stores the number of elements in the list. It
points to the first data element of the list.
35. List three examples that uses linked list?
Polynomial ADT
Radix sort
Multi lists
36. Give some examples for linear data structures?
Stack
Queue
37. Write postfix from of the expression A+B-C+D?
A-B+C-D
38. How do you test for an empty queue?
To test for an empty queue, we have to check whether READ=HEAD where REAR is a pointer pointing to
the last node in a queue and HEAD is a pointer that pointer to the dummy header. In the case of array
implementation of queue, the condition to be checked for an empty queue is READ<front.
39. What are the postfix and prefix forms of the expression?
A+B*(C-D)/(P-R)
Postfix form: ABCD-*PR-/+
Prefix form: +A/*B-CD-PR
40. Explain the usage of stack in recursive algorithm implementation?
In recursive algorithms, stack data structures is used to store the return address when a recursive call is
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 39/63
encountered and also to store the values of all the parameters essential to the current state of the
procedure.
41. Write down the operations that can be done with queue data structure?
Queue is a first - in -first out list. The operations that can be done with queue are insert and remove.
42. What is a circular queue?
The queue, which wraps around upon reaching the end of the array is called as circular queue.
43. Define max heap?
A heap in which the parent has a larger key than the child's is called a max heap.
44. Define min heap?
A heap in which the parent has a smaller key than the child is called a min heap.
PART B
1. How do you analyses an algorithm?
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 40/63
Algorithm analysis refers to the process of determining how much computing time and storage that
algorithms will require. In other words, its a process of predicting the resource requirement of
algorithms in a given environment.
In order to solve a problem, there are many possible algorithms. One has to be able to choose the best
algorithm for the problem at hand using some scientific method. To classify some data structures and
algorithms as good, we need precise ways of analyzing them in terms of resource requirement. Themain resources are:
Running Time
Memory Usage
Communication Bandwidth
Running time is usually treated as the most important since computational time is the most precious
resource in most problem domains.
There are two approaches to measure the efficiency of algorithms:
Empirical: Programming competing algorithms and trying them on different instances.
Theoretical: Determining the quantity of resources required mathematically (Execution time, memory
space, etc.) needed by each algorithm.
However, it is difficult to use actual clock-time as a consistent measure of an algorithms efficiency,
because clock-time can vary based on many things. For example,
Specific processor speed
Current processor load
Specific data for a particular run of the program
o Input Size
o Input Properties
Operating Environment
Accordingly, we can analyze an algorithm according to the number of operations required, rather than
according to an absolute amount of time involved. This can show how an algorithms efficiency changes
according to the size of the input.
Complexity Analysis
Complexity Analysis is the systematic study of the cost of computation, measured either in time units or
in operations performed, or in the amount of storage space required.
The goal is to have a meaningful measure that permits comparison of algorithms independent of
operating platform.
There are two things to consider:
Time Complexity: Determine the approximate number of operations required to solve a problem of
size n.
Space Complexity: Determine the approximate memory required to solve a problem of size n.
Complexity analysis involves two distinct phases:
Algorithm Analysis: Analysis of the algorithm or data structure to produce a function T (n) that
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 41/63
describes the algorithm in terms of the operations performed in order to measure the complexity of the
algorithm.
Order of Magnitude Analysis: Analysis of the function T (n) to determine the general complexity
category to which it belongs.
There is no generally accepted set of rules for algorithm analysis. However, an exact count of operationsis commonly used.
Analysis Rules:
1. We assume an arbitrary time unit.
2. Execution of one of the following operations takes time 1:
Assignment Operation
Single Input/Output Operation
Single Boolean Operations
Single Arithmetic Operations
Function Return
3. Running time of a selection statement (if, switch) is the time for the condition evaluation + the
maximum of the running times for the individual clauses in the selection.
4. Loops: Running time for a loop is equal to the running time for the statements inside the loop *
number of iterations.
The total running time of a statement inside a group of nested loops is the running time of the
statements multiplied by the product of the sizes of all the loops.
For nested loops, analyze inside out.
Always assume that the loop executes the maximum number of iterations possible.
5. Running time of a function call is 1 for setup + the time for any parameter calculations + the time
required for the execution of the function body.
Examples:
1. int count(){
int k=0;
cout<< Enter an integer;
cin>>n;
for (i=0;i<n;i++)
k=k+1;
return 0;}
Time Units to Compute
-------------------------------------------------
1 for the assignment statement: int k=0
1 for the output statement.
1 for the input statement.
In the for loop:
1 assignment, n+1 tests, and n increments.
n loops of 2 units for an assignment, and an addition.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 42/63
1 for the return statement.
-------------------------------------------------------------------
T (n)= 1+1+1+(1+n+1+n)+2n+1 = 4n+6 = O(n)
2. int total(int n)
{int sum=0;
for (int i=1;i<=n;i++)
sum=sum+1;
return sum;
}
Time Units to Compute
-------------------------------------------------
1 for the assignment statement: int sum=0
In the for loop:
1 assignment, n+1 tests, and n increments.
n loops of 2 units for an assignment, and an addition.
1 for the return statement.
-------------------------------------------------------------------
T (n)= 1+ (1+n+1+n)+2n+1 = 4n+4 = O(n)
3. void func()
{
int x=0;
int i=0;
int j=1;
cout<< Enter an Integer value;
cin>>n;
while (i<n){
x++;
i++;
}
while (j<n)
{
j++;
}
}
Time Units to Compute
-------------------------------------------------
1 for the first assignment statement: x=0;
1 for the second assignment statement: i=0;
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 43/63
1 for the third assignment statement: j=1;
1 for the output statement.
1 for the input statement.
In the first while loop:
n+1 tests
n loops of 2 units for the two increment (addition) operationsIn the second while loop:
n tests
n-1 increments
-------------------------------------------------------------------
T (n)= 1+1+1+1+1+n+1+2n+n+n-1 = 5n+5 = O(n)
4. int sum (int n)
{
int partial_sum = 0;
for (int i = 1; i <= n; i++)
partial_sum = partial_sum +(i * i * i);
return partial_sum;
}
Time Units to Compute
-------------------------------------------------
1 for the assignment.
1 assignment, n+1 tests, and n increments.
n loops of 4 units for an assignment, an addition, and two multiplications.
1 for the return statement.
-------------------------------------------------------------------
T (n)= 1+(1+n+1+n)+4n+1 = 6n+4 = O(n)
Formal Approach to Analysis
In the above examples we have seen that analysis so complex. However, it can be simplified by using
some formal approach in which case we can ignore initializations, loop control, and book keeping.
For Loops: Formally
In general, a for loop translates to a summation. The index and bounds of the summation are the same
as the index and bounds of the for loop.
Suppose we count the number of additions that are done. There is 1 addition per iteration of the loop,
hence N additions in total.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 44/63
Nested Loops: Formally
Nested for loops translate into multiple summations, one for each for loop.
Again, count the number of additions. The outer summation is for the outer for loop.
Consecutive Statements: Formally
Add the running times of the separate blocks of your code
Conditionals: Formally
If (test) s1 else s2: Compute the maximum of the running time for s1 and s2.
2. Explain how pointer are used to implement linked list structure.
A linked list is a data structure that is built from structures and pointers. It forms a chain of "nodes" with
pointers representing the links of the chain and holding the entire thing together. A l inked list can be
represented by a diagram like this one:
This linked list has four nodes in it, each with a link to the next node in the series. The last node has a
link to the special value NULL, which any pointer (whatever its type) can point to, to show that it is the
last link in the chain. There is also another special pointer, called Start (also called head), which points to
the first link in the chain so that we can keep track of it.
Defining the data structure for a linked list
The key part of a linked list is a structure, which holds the data for each node (the name, address, age or
whatever for the items in the list), and, most importantly, a pointer to the next node. Here we have
given the structure of a typical node:
struct node
{ char name[20]; // Name of up to 20 letters
int age
float height; // In metres
node *nxt;// Pointer to next node
};
struct node *start_ptr = NULL;
The important part of the structure is the line before the closing curly brackets. This gives a pointer to
the next node in the list. This is the only case in C++ where you are allowed to refer to a data type (in
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 45/63
this case node) before you have even finished defining it!
We have also declared a pointer called start_ptr that will permanently point to the start of the list. To
start with, there are no nodes in the list, which is why start_ptr is set to NULL.
3. Explain various operation performed on the doubly l inked list.
Doubly Linked Lists
That sounds even harder than a linked list! Well, if you've mastered how to do singly linked lists, then it
shouldn't be much of a leap to doubly linked lists
A doubly linked list is one where there are links from each node in both directions:
You will notice that each node in the list has two pointers, one to the next node and one to the previous
one - again, the ends of the list are defined by NULL pointers. Also there is no pointer to the start of the
list. Instead, there is simply a pointer to some position in the list that can be moved left or right.
The reason we needed a start pointer in the ordinary linked list is because, having moved on from one
node to another, we can't easily move back, so without the start pointer, we would lose track of all the
nodes in the list that we have already passed. With the doubly linked list, we can move the current
pointer backwards and forwards at will.
Creating Doubly Linked Lists
The nodes for a doubly linked list would be defined as follows:
struct node{
char name[20];
node *nxt; // Pointer to next node
node *prv; // Pointer to previous node
};
node *current;
current = new node;
current->name = "Fred";
current->nxt = NULL;
current->prv = NULL;
We have also included some code to declare the first node and set its pointers to NULL. It gives the
following situation:
We still need to consider the directions 'forward' and 'backward', so in this case, we will need to define
functions to add a node to the start of the list (left-most position) and the end of the list (right-most
position).
Adding a Node to a Doubly Linked List
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 46/63
void add_node_at_start (string new_name)
{ // Declare a temporary pointer and move it to the start
node *temp = current;
while (temp->prv != NULL)
temp = temp->prv;
// Declare a new node and link it innode *temp2;
temp2 = new node;
temp2->name = new_name; // Store the new name in the node
temp2->prv = NULL; // This is the new start of the list
temp2->nxt = temp; // Links to current list
temp->prv = temp2;
}
void add_node_at_end ()
{ // Declare a temporary pointer and move it to the end
node *temp = current;
while (temp->nxt != NULL)
temp = temp->nxt;
// Declare a new node and link it in
node *temp2;
temp2 = new node;
temp2->name = new_name; // Store the new name in the node
temp2->nxt = NULL; // This is the new start of the list
temp2->prv = temp; // Links to current list
temp->nxt = temp2;
}
Here, the new name is passed to the appropriate function as a parameter. We'll go through the function
for adding a node to the right-most end of the list. The method is similar for adding a node at the other
end. Firstly, a temporary pointer is set up and is made to march along the list until it points to last node
in the list.
After that, a new node is declared, and the name is copied into it. The nxt pointer of this new node is set
to NULL to indicate that this node will be the new end of the list.
The prv pointer of the new node is linked into the last node of the existing list.
The nxt pointer of the current end of the list is set to the new node.
4. Give linked list implementation of stack operation.
Linked List Implementation of Stacks: the PUSH operation
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 47/63
Its very similar to the insertion operation in a dynamic singly linked list. The only difference is that here
you'll add the new element only at the end of the list, which means addition can happen only from the
TOP. Since a dynamic list is used for the stack, the Stack is also dynamic, means it has no prior upper
limit set. So, we don't have to check for the Overflow condition at all!
In Step [1] we create the new element to be pushed to the Stack.
In Step [2] the TOP most element is made to point to our newly created element.
In Step [3] the TOP is moved and made to point to the last element in the stack, which is our newly
added element.
Linked List Implementation of Stacks: the POP Operation
This is again very similar to the deletion operation in any Linked List, but you can only delete from the
end of the list and only one at a time; and that makes it a stack. Here, we'll have a list pointer, "target",
which will be pointing to the last but one element in the List (stack). Every time we POP, the TOP most
element will be deleted and "target" will be made as the TOP most element.
In step[1] we got the "target" pointing to the last but one node.
In step[2] we freed the TOP most element.
In step[3] we made the "target" node as our TOP most element.
Supposing you have only one element left in the Stack, then we won't make use of "target" rather we'll
take help of our "bottom" pointer. See how...
Algorithm:
Step-1: If the Stack is empty then give an alert message "Stack Underflow" and quit; or else proceed
Step-2: If there is only one element left go to step-3 or else step-4
Step-3: Free that element and make the "stack", "top" and "bottom" pointers point to NULL and quit
Step-4: Make "target" point to just one element before the TOP; free the TOP most element; make
"target" as your TOP most element
Implementation:
struct node
{
int nodeval;
struct node *next;
}
struct node *stack = NULL; /*stack is initially empty*/
struct node *top = stack;
main()
{
int newvalue, delval;
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 48/63
..
push(newvalue);
..
delval = pop(); /*POP returns the deleted value from the stack*/
}
int pop( ){
int pop_val = 0;
struct node *target = stack;
if(stack == NULL) /*step-1*/
cout<<"Stack Underflow";
else
{
if(top == bottom) /*step-2*/
{
pop_val = top -> nodeval; /*step-3*/
delete top;
stack = NULL;
top = bottom = stack;
}
else /*step-4*/
{
while(target->next != top) target = target ->next;
pop_val = top->nodeval;
delete top;
top = target;
target ->next = NULL;
}
}
return(pop_val);
}
5. What is a stack? Explain any two operations performed on a stack with required algorithm.
Stacks
A simple data structure in which insertion and deletion occur at the same end, is termed (called) a stack.
It is a LIFO (Last In First Out) structure.
The operations of insertion and deletion are called PUSH and POP
Push - push (put) item onto stack
Pop - pop (get) item from stack
Initial Stack Push(8) Pop
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 49/63
TOS=>
4
1
3
6
TOS=>
8
4
1
3
6
TOS=>
4
1
3
6
Our Purpose:
To develop a stack implementation that does not tie us to a particular data type or to a particular
implementation.
Implementation:
Stacks can be implemented both as an array (contiguous list) and as a linked list. We want a set of
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 50/63
operations that will work with either type of implementation: i.e. the method of implementation is
hidden and can be changed without affecting the programs that use them.
The Basic Operations:
Push()
{
if there is room {
put an item on the top of the stack
else
give an error message
}
}
Pop()
{
if stack not empty {
return the value of the top item
remove the top item from the stack
}
else {
give an error message
}
}
CreateStack()
{
remove existing items from the stack
initialise the stack to empty
}
Array Implementation of Stacks: The PUSH operation
Here, as you might have noticed, addition of an element is known as the PUSH operation. So, if an array
is given to you, which is supposed to act as a STACK, you know that it has to be a STATIC Stack; meaning,
data will overflow if you cross the upper limit of the array. So, keep this in mind.
Algorithm:
Step-1: Increment the Stack TOP by 1. Check whether it is always less than the Upper Limit of the stack.
If it is less than the Upper Limit go to step-2 else report -"Stack Overflow"
Step-2: Put the new element at the position pointed by the TOP
Implementation:
static int stack[UPPERLIMIT];
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 51/63
int top= -1; /*stack is empty*/
..
..
main()
{
..
..
push(item);
..
..
}
push(int item)
{
top = top + 1;
if(top < UPPERLIMIT)
stack[top] = item; /*step-1 & 2*/
else
cout<<"Stack Overflow";
}
Note:- In array implementation,we have taken TOP = -1 to signify the empty stack, as this simplifies the
implementation.
Array Implementation of Stacks: the POP operation
POP is the synonym for delete when it comes to Stack. So, if you're taking an array as the stack,
remember that you'll return an error message, "Stack underflow", if an attempt is made to Pop an item
from an empty Stack. OK.
Algorithm
Step-1: If the Stack is empty then give the alert "Stack underflow" and quit; or else go to step-2
Step-2: a) Hold the value for the element pointed by the TOP
b) Put a NULL value instead
c) Decrement the TOP by 1
Implementation:
static int stack[UPPPERLIMIT];
int top=-1;
..
..
main()
{
..
..
poped_val = pop();
..
..
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 52/63
}
int pop()
{
int del_val = 0;
if(top == -1)
cout<<"Stack underflow"; /*step-1*/else
{
del_val = stack[top]; /*step-2*/
stack[top] = NULL;
top = top -1;
}
return(del_val);
}
Note: - Step-2:(b) signifies that the respective element has been deleted.
Algorithm
Step-1: If the Stack is empty go to step-2 or else go to step-3
Step-2: Create the new element and make your "stack" and "top" pointers point to it and quit.
Step-3: Create the new element and make the last (top most) element of the stack to point to it
Step-4: Make that new element your TOP most element by making the "top" pointer point to it.
Implementation:
struct node{
int item;
struct node *next;
}
struct node *stack = NULL; /*stack is initially empty*/
struct node *top = stack;
main()
{
..
..
push(item);
..
}
push(int item)
{
if(stack == NULL) /*step-1*/
{
newnode = new node /*step-2*/
newnode -> item = item;
newnode -> next = NULL;
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 53/63
stack = newnode;
top = stack;
}
else
{
newnode = new node; /*step-3*/newnode -> item = item;
newnode -> next = NULL;
top ->next = newnode;
top = newnode; /*step-4*/
}
}
6. State and explain the priority queue with example.
Priority Queue
- is a queue where each data has an associated key that is provided at the time of insertion.
- Dequeue operation deletes data having highest priority in the list
- One of the previously used dequeue or enqueue operations has to be modified
Example: Consider the following queue of persons where females have higher priority than males
(gender is the key to give priority).
Dequeue()- deletes Aster
Dequeue()- deletes Meron
Now the queue has data having equal priority and dequeue operation deletes the front element like in
the case of ordinary queues.
Dequeue()- deletes Abebe
Dequeue()- deletes Alemu
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 54/63
Thus, in the above example the implementation of the dequeue operation need to be modified.
7. What are the various method involved to solve hashing function?
8. Explain, with example the basic heap operations and write the algorithms for the same.
Heap Sort
Heap sort operates by first converting the list in to a heap tree. Heap tree is a binary tree in which each
node has a value greater than both its children (if any). It uses a process called "adjust to accomplish its
task (building a heap tree) whenever a value is larger than its parent. The time complexity of heap sort is
O(nlogn).
Algorithm:
1. Construct a binary tree
The root node corresponds to Data[0].
If we consider the index associated with a particular node to be i, then the left child of this node
corresponds to the element with index 2*i+1 and the right child corresponds to the element with index
2*i+2. If any or both of these elements do not exist in the array, then the corresponding child node does
not exist either.
2. Construct the heap tree from initial binary tree using "adjust" process.
3. Sort by swapping the root value with the lowest, right most value and deleting the lowest, right most
value and inserting the deleted value in the array in it proper position.
Example: Sort the following list using heap sort algorithm.
5 8 2 4 1 3 9 7 6 0
<a;
<div(a,b);
<a<<\n<<b;
<a<<\n<<b;
<front.<n;i++)
<n){
<n)
Swap the root node with the lowest, right most node and delete the lowest, right most value; insert the
deleted value in the array in its proper position; adjust the heap tree; and repeat this process until the
tree is empty.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 55/63
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 56/63
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 57/63
UNIT 4NONLINEAR DATA STRUCTURES
Trees-Binary trees, search tree ADT, AVL trees, Graph Algorithms-Topological sort, shortest path
algorithm network flow problems-minimum spanning tree - Introduction to NP - completeness.
PART A
1. Define non-linear data structure?
Data structure which is capable of expressing more complex relationship than that of physical adjacency
is called non-linear data structure.
2. Define tree?
A tree is a data structure, which represents hierarchical relationship between individual Data items.
3. Define leaf?
In a directed tree any node which has out degree o is called a terminal node or a leaf.
4. What is a Binary tree?
A 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.
5. What are the applications of binary tree?
Binary tree is used in data processing.
a. File index schemes
b. Hierarchical database management system
6. What is meant by traversing?
Traversing a tree means processing it in such a way, that each node is visited only once.
7. What are the different types of traversing?
The different types of traversing are
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 58/63
a. Pre-order traversal-yields prefix from of expression.
b. In-order traversal-yields infix form of expression.
c. Post-order traversal-yields postfix from of expression.
8. What are the two methods of binary tree implementation?
Two methods to implement a binary tree are,
a. Linear representation.
b. Linked representation
9. Define Graph?
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).
10. Define adjacent nodes?
Any two nodes which are connected by an edge in a graph are called adjacent nodes. For Example, if and
edge xÎE is associated with a pair of nodes (u,v) where u, v Î V, then we say that the edge x connects the
nodes u and v.
11.Name the different ways of representing a graph?
a. Adjacency matrix
b. Adjacency list
12. What are the two traversal strategies used in traversing a graph?
a. Breadth first search
b. Depth first search
13. What is an acyclic graph?
A simple diagram which does not have any cycles is called an acyclic graph.
14. Give some example of NP complete problems.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 59/63
? Hamiltonian circuit.
? Travelling salesmen problems
? Longest path problems
? Bin packing
? Knapsack problem
? Graph colouring problem
PART B
1. Explain Dijkstras algorithm using the following graph. Find the shortes path between
v1,v2,v3,v4,v5,v6 & v7. (May/June 2007)
2. Write ADT operation for Prims Algorithm. (8) (May/June 2007)
3. Explain the topological sort algorithm. (8) (May/June 2007)
4. Write suitable ADT operation for shortest path problem. Show the simulation of shortest path with an
example graph. (April/May 2008)
5. How do you construct a minimum cost spanning tree with Prims algorithm? (8) (April/May 2008)
6. Explain depth first search on a graph with necessary data structures. (8) (April/May 2008)
7. Discuss and write the program to perform topological sorting. (8) (April/May 2007)
8. What is single source shortest path problem? Discuss Dijkstras single source shortest path algorithm
with an example. (8) (April/May 2007)
9. Write an algorithm to find the minimum cost spanning tree of an undirected weighted graph. (8)
(April/May 2007)
10. Explain Depth first & Breadth First Traversal algorithms.
11. Explain Kruskals algorithm with an example.
12. Explain Prims algorithm with an example.
UNIT 5
SORTING AND SEARCHING
Sorting Insertion sort, Shell sort, Heap sort, Merge sort, Quick sort, Indirect sorting, Bucket sort,
Introduction to Algorithm Design Techniques Greedy algorithm (Minimum Spanning Tree), Divide and
Conquer (Merge Sort), Dynamic Programming (All pairs Shortest Path Problem).
PART A
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 60/63
1. What is meant by sorting?
2. What are the two main classifications of sorting based on the source of data?
3. What is meant by external sorting?
4. What is meant by internal sorting?
5. What are the various factors to be considered in deciding a sorting algorithm?
6. What is the main idea behind insertion sort?7. What is the basic idea of shell sort?
8. What is the purpose of quick sort?
9. What is the advantage of quick sort?
10. What is the average efficiency of heap sort?
11. Define Algorithm.
12. What is complexity analysis?
13. What is performance analysis of an algorithm?
14. Define space complexity.
15. Define time complexity.
16. What does asymptotic notation mean?
17. Define best case, average case & worst case of an algorithm. Give an example for
each.
18. What is divide and conquer technique?
19. Define Greedy algorithm.
20. What is dynamic programming? (April/May 2006)
*********
1. What is meant by sorting?
Ordering the data in an increasing or decreasing fashion according to some relationship among the data
item is called sorting.
2. What are the two main classifications of sorting based on the source of data?
a. Internal sorting
b. External sorting
3. What is meant by external sorting?
External sorting is a process of sorting in which large blocks of data stored in storage Devices are moved
to the main memory and then sorted.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 61/63
4. What is meant by internal sorting?
Internal sorting is a process of sorting the data in the main memory.
5. What are the various factors to be considered in deciding a sorting algorithm?
a. Programming time
b. Execution time of the program
c. Memory needed for program environment
6. What is the main idea in Bubble sort?
The basic idea underlying the bubble sort is to pass through the file sequentially
Several times. Each pass consists of comparing each element in the file with its
successor (x[i] and x[i+1] and interchanging the two elements if they are not in proper
order.
7. What is the basic idea of shell sort?
Instead of sorting the entire array at once, it is first divide the array into smaller
segments, which are then separately sorted using the insertion sort.
8. What is the purpose of quick sort?
The purpose of the quick sort is to move a data item in the correct direction, just
enough for to reach its final place in the array.
9. What is the advantage of quick sort?
Quick sort reduces unnecessary swaps and moves an item to a greater distance, in one move.
10. What is the average efficiency of heap sort?
The average efficiency of heap sort is 0 (n(log2 n)) where, n is the number of
elements sorted.
11. Define Algorithm.
An algorithm is clearly specified set of simple instructions to be followed to
solve a problem. The algorithm forms a base for program.
12. What is complexity analysis?
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 62/63
It is the analysis of the amount of memory and time an algorithm requires to
completion.
There are two types of Complexity
Space Complexity
Time Complexity
13. What is performance analysis of an algorithm?
The analysis of the performance of an algorithm based on specification is called
performance analysis. It is loosely divided into
a. Priori estimates
b. Posterior Testing
14. Define space complexity.
Space complexity of an algorithm is the amount of memory it needs to run to
completion.
15. Define time complexity.
Time complexity is the amount of computer time an algorithm requires to run
to completion.
16. What does asymptotic notation mean?
Asymptotic notations are terminology that is introduced to enable us to make
meaningful statements about the time and space complexity of an algorithm.
The different notations are
Big Oh notation
Omega notation
Theta notation.
17. Define best case of an algorithm.
It is the shortest time that an algorithm will use over all instances of size n for
a given problem to produce the result.
8/6/2019 Regulation 2009 Ec 2202 Data Structures and Object Oriented
http://slidepdf.com/reader/full/regulation-2009-ec-2202-data-structures-and-object-oriented 63/63
18. What is divide and conquer technique?
Divide and Conquer algorithm is based on dividing the problem to be solvedinto several, smaller sub instances, solving them independently and then combining
the sub instances solutions so as to yield a solution for the original instance.
19. What is dynamic programming?
Dynamic programming algorithm is a general class of algorithms which solve
problems by solving smaller versions of the problem, saving the solutions to the
small problems and then combining them to solve the larger problems.
20. Define Greedy method.
The greedy method suggests that one can devise an algorithm that works in stages, considering one
input at a time. At each stage, a decision is made regarding whether a particular input is an optimal
solution. An example for solution using greedy method is knapsack problem.
PART B
1. Write a short note on analysis of algorithm. Discuss the various notations and their complexities.
2. Explain dynamic programming with a suitable example.
3. Explain the various notations used in the analysis of algorithms.
4. Explain any two algorithm design techniques with suitable examples.
5. Explain divide & conquer technique with a suitable example.
6. Derive the best, average, worst case time complexity of a linear search. (May/June 2007)
7. With an example, explain how you will measure the efficiency of an algorithm. (8) (April/May 2008)
8. Write quick sort algorithm and explain.
9. State and explain the algorithm to perform heap sort.
10. State and explain the huffmans algorithm