0% found this document useful (0 votes)
25 views210 pages

Cs 3rd Semester

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

Cs 3rd Semester

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

UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III

UNIT
1 Fundamental Concepts, Linear
Data Structure Using Arrays and
Stacks

SYLLABUs
Fundamental Concepts: Introduction to Data Structures, Types of Data Structures, Introduction
to Algorithm, Pseudo-code, Flowchart, Analysis of Algorithms.

Linear Data Structure Using Arrays: 1-D Arrays, 2-D Arrays, N-D Arrays, Memory Representation
and Address Calculation of 1-D, 2-D, N-D Arrays, Concept of Ordered Lists, String Manipulation,
Pros and Cons of Arrays.

Stacks: Concept, Primitive Operations, Abstract Data Type, Representation Stacks Using Arrays,
Prefix, Infix, Postfix Notations for Arithmetic Expression, Applications of Stacks – Converting
Infix Expression to Postfix Expression, Evaluating the Postfix Expression, Checking Well-formed
(Nested) Parenthesis, Processing of Function Calls, Reversing a String.

LEARNING OBJECTIVEs
 Meaning and Types of Data Structure.
 Linear Data Structure Using Arrays.
 Memory Representation and Address Calculation of 1-D, 2-D and N-D Arrays.
 Stack and its Representation using Arrays.
 Prefix, Infix, Postfix Notations for Arithmetic Expressions.
 Applications of Stacks.

INTRoDUCTIoN
Data Structure is defined as a specialized format for organizing and storing data in
memory. These structures can be either linear like array, stack, queue, linked-list or
non-linear like trees and graphs. The operations performed on these structures can be
represented using ADT, which consists of set of data types. The performance of each of
the structure is computed based on time and space complexities.

Linear data structure is a category of data structure in which data elements are arranged in
a sequential fashion. Some linear data structure includes linked list, queue, stack and array.
Array is a variable which is capable of holding fixed values in contiguous memory locations.
Stack stores ordered set of elements in a sequential fashion. In stack, new elements can be
inserted and the existing elements can be deleted from only one end called top of stack.

1 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

P a r t- A S h o rt Q u e s t i o n s a n d A n s w e r s
Q1. Define data structure and describe the types of data structure.
Answer : (Model Paper-I, Q3 | Nov./Dec.-19, Q1 [OU])

Data Structure
Data structure can be defined as a way of organizing the data in the memory. Here data denotes a set of data
elements and set of operations performed on it. Data structures are independent from their implementation and need
some programming language to implement it.
Types of Data Structure
Different types of data structures are as follows,
1. Primitive and non-primitive
2. Linear and non-linear
3. Static and dynamic
I am Simple and Easy
4. Persistent and ephemeral
5. Sequential and direct access.
Q2. Define a Data structure in terms of the triplet (D, F, A). Give an example.
Answer : June/July-19, Q1 [OU]

A data structure ‘d’ can be defined as a triplet d = (D, F, A) containing data objects (D), function (F) and set
of rules (A) respectively to implement the operations on data objects.
Example: Consider a complex number z = a + ib, where a and b are of real data type.
Domain
Complex z
{
a : Real
b : Real
}
Let, z1 = a1 + ib1 and z2 = a2 + ib2 be two data objects.
Function
F = {Å, –, Ä}
Axioms
A = {z = z1 Å z2 = (a1 + a2) + i (b1 + b2)
z = z1 – z2 = (a1 – a2) + i (b1 – b2)
z = z1 Ä z2 = (a1a2 – b1b2) + i (a1b2 + a2 b1)}
Q3. What is the difference between Atomic and Composite data with examples?
Answer : Nov./Dec.-18, Q1 [OU]

Atomic Data
The atomic data is defined as the data which is viewed as single and non decomposable entity by the user.
Due to its numerical properties, the atomic data can also be called as scalar data.
Example
Consider an integer 5678. It can be decomposed into single digits i.e., (5, 6, 7, 8). However, after decomposition
these digits doesn’t hold the same characteristics as the actual integer i.e., (5678) does. Thus, the atomic data is
considered as single and non decomposable data.

Publishers and Distributors Pvt. Ltd. 2


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Composite Data Q6. Define array. Explain how to declare an
The composite data is defined as the data which array with example.
can be decomposed into several meaningful subfields. It Answer : Model Paper-I, Q1
can also be called as structured data and it is implemented Array
in C++ by using structure, class etc. It is a variable which is capable of holding fixed
Example values in contiguous memory locations. The general
Consider an employee’s record which contains format of an array is,
fields such as employee ID, name, salary etc. Each an
a0 a1 a2 .. .. .. ..
employee record is decomposed into several sub-fields
(i.e., employee ID, name, salary). Thus, the composite data
Declare an Array
can be decomposed without any change in its meaning.
An array can be declared in the following manner,
Q4. Define an algorithm. Write the essential
characteristics of an algorithm. type array_name[size];
Answer : (Model Paper-III, Q3 | May/June-18, Q1 [OU]) Here ‘type’ represents the data type of array
being defined, ‘array_name’ is the name of the array. The
Algorithm
subscript at the end contains a parameter called ‘size’
An algorithm is a method of representing the step- which specifies the maximum number of elements that
by-step procedure for solving a problem. An algorithm can be stored in an array.
is very useful for finding the right answer to a problem
Example: int xyz[8];
by breaking the problem into simple cases.
Here, xyz is an array of 8 integers.
Characteristics of Algorithm
Q7. What is a one-dimensional array?
The essential characteristics of an algorithm are
as follows, Answer :
1. Finiteness One-dimensional Array
2. Definiteness One-dimensional array is a simple array in which
elements are stored in contiguous memory locations.
3. Effectiveness
Array elements are accessed using one subscript.
4. Generality
Syntax: datatype array_name [size];
5. Input/Output.
Example: int a[4];
Q5. Decine flowchart. What is the use of flow-
Here, a is an array of 4 integers.
chart? Model Paper-II, Q1
Q8. Define two-dimensional array.
OR
po r t
ant Like Wa
ter Answer : Model Paper-III, Q2
What is Flowchart? Im
Two-dimensional Array
Answer : May/June-19, Q1 [MGU]
A two-dimensional array is an array of two
Flowchart
dimensions. It stores data in the form of rows and columns.
Flowchart is a diagrammatic
representation of an algorithm. It is When the data must be stored in the form of a
built using different types of boxes matrix we use two-dimensional arrays.
and symbols. The operation to be performed is written Syntax: type array_name[row_size] [column_size];
in the box. All symbols are interconnected by arrows to Example: int a[5][3];
indicate the flow of information and processing. Above declaration represents a two-dimensional
Use of Flowchart array consisting of 5 rows and 3 columns. So the total
Flowchart is used for the following purposes, number of elements which can be stored in this array are
(i) To assist the programmer in developing the 5 × 3 i.e., 15.
program logic and to be used as documentation Q9. What are pros and cons of Arrays?
for a complete program. Nov./Dec.-18, Q1 [MGU]
(ii) To analyze or define a process. OR
(iii) To explain in detail about the actions and Write the advantages and
decisions defined in the process (i.e., it can be disadvantages of arrays.
used as a communication or training aid).
Answer : Nov./Dec.-17, Q1 [OU]
(iv) To assist the programmer, while searching
potential problem points in a process. Pros/Advantages of Arrays
(v) To help the programmer, while examining the 1. They are used to store the fixed size data. They
performance of a process. also support the high frequency of data retrievals.

3 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
2. They allow data to be accessed randomly and Disadvantages
directly in 0(1) time.
(i) The memory allocation is static in nature, so the
3. They are used to represent the data structures like allocated size can’t be changed.
stacks, queues and the complex data structures
(ii) The size that has to be allotted should be known
like heaps and hash tables.
prior to the execution.
Cons/Disadvantages of Arrays
(iii) Insertions and deletions in between the list are
1. The size of an array cannot be changed during costly because they requires data movement/
run-time because it supports static memory shifting at larger extent. Thus, it affects the time
management. complexity and space complexity.
2. They can be declared with some arbitrary Q11. Define stack. List the operations of stack.
maximum size to avoid the problem of array
being static. This leads to below problems. Answer : (Model Paper-I, Q2 | Nov./Dec.-19, Q2 [MGU])

(a) User cannot exceed the given limit even in Stack


required cases. Stack is a linear data struc-
(b) For small computations, the program uses ture. The elements in a stack can be
less memory and the remaining reserved inserted and deleted at only one end
memory will be wasted. This leads to called ton. Stack is also said to be
Keep an eye on me
wastage and poor utilization of memory. Last-In-First Out (LIFO).

Q10. What is Sequential Organization? Briefly Operations of Stack


explain its advantages and disadvantages. The two essential operations performed on a
stack are,
Answer : Nov./Dec.-18, Q2 [OU]
1. Push
Sequential Organization
When an element is added to a stack, such kind
Sequential organization is a technique in which
of operation is called push.
all the data elements are stored in a sequential manner.
Besides this, there is a distinct successor and/or a distinct 2. Pop
predecessor that is associated with every data element in
When an element is deleted from a stack, such
the sequence. It stores the data at some fixed intervals of
kind of operation is called pop.
distance. For instance, if an element ‘x’ is located at ‘z’
and then its next element i.e., (x + 1)th element is located Q12. Define ADT.
at (z + c), where c = constant.
Answer :
Few examples of sequential organization are
Linear Arrays, Linear queues and Linear stacks. Abstract Data Types (ADT) are the user-defined
data types that exhibits the same characteristics as
Example predefined data types.
Consider the elements 10, 20, 30 and 40 stored An ADT refers to a data type that must satisfy
sequentially with a starting address location ‘z’ and a constant the following two requirements.
(c) = 1.
1. A single syntactic unit must contain the type
Sequential
10 20 30 40 declarations and the operations that can be
Organization
performed on objects of the declared type which
location location location location gives the types interface. The implementation of
z z+1 z+2 z+3 the type along with its operations can be written
either in the same or the different syntactic unit.
Advantages
2. The objects representation (of the declared type)
(i) It provides direct access to any element present is completely hidden from the program unit that
in the list within a constant time duration. uses the type. So, the direct operations that can
(ii) It stores data in continuous memory locations due be performed on the objects are those specified
to which it takes constant time for accessing data in the types definition.
despite of its length. Simula 67 was the first language that uses ADT.
(iii) The data elements in the list need not store the Later, many languages such as Ada, Modula-2, C++ and
address of their successive elements. Java supports it.

Publishers and Distributors Pvt. Ltd. 4


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Q13. List the ADT operations of stack. Q15. Define postfix expression.
Answer : Model Paper-II, Q2 Answer :
The ADT operations for stack are as follows, Postfix Expression
create( ) : Returns the address of a stack node. In postfix notation, the operator is placed after the
destroy( ) : Returns null pointer by deleting all operands. It is also referred to as reverse polish notation.
the nodes in a stack. Example
push( ) : Inserts an element at the top end AB +
of the stack. ABC +*
pop( ) : Deletes an element stored at the AB + Z +
top end of the stack. AC* BD*+
count( ) : Returns the total number of Q16. Define infix expression.
elements in a stack.
Answer : (Model Paper-III, Q1 | Nov./Dec.-19, Q1 [MGU])
empty( ) : Checks whether the stack is empty,
Infix Expression
if it is, it returns ‘true’. Otherwise,
it returns ‘false’. In infix notation, the operator is placed between
the two operands. Most of the arithmetic expressions are
full( ) : Checks whether the stack is full if
expressed using this notation.
it is, it returns ‘true’ otherwise, it
returns ‘false’. Example
Q14. What is stack? List out applications of A+B
stack. (Model Paper-II, Q3 | Nov./Dec.-19, Q2 [OU]) A*B+C
OR (A + B) + C
List the applications of stacks. (A * C) + (B * D).
(Refer Only Topic: Applications of Stack) Q17. What are the advantages of prefix and
May-18, Q1 [MGU]
postfix expression?
OR Answer : June/July-19, Q2 [OU]
The advantages of prefix and postfix expressions
What are the applications of stacks?
are as follows,
(Refer Only Topic: Applications of Stack)
1. They are useful in describing tree traversal.
Answer : June/July-19, Q3 [OU]
2. They can be computed by using stack.
Stack
3. They place each operator according to its
For answer refer Unit-I, Page No. 4, precedence. As a result, ambiguity is eliminated
Q.No. 11, Topic: Stack. which interpreting arithmetic expressions.
Applications of Stack 4. They act as a good application for stacks.
The applications of stack are as follows, 5. They do not require parenthesis to be used in
1. Stacks are used in conversion of expression from expression. As a consequence, they do not have
infix notation to postfix and prefix notation. the overhead of parentheses in case of nested
expressions.
2. Stacks are used for evaluation of infix and postfix
Q18. Explain the postfix expression evaluation
forms.
with an example.
3. Stacks are used in tree traversal techniques. Answer : Nov./Dec.-17, Q2 [OU]
4. Recursive functions are implemented using Evaluation of Postfix Expression using Stack
stacks. The copies of variables at each level of
The steps involved in evaluating a postfix
recursion are stored in stack.
expression are as follows,
5. Compilers use stacks in syntax analysis phase 1. Initially, scan the given input from left to right,
to check whether a particular statement in a pro- move the operands on to the stack until any
gram is syntactically correct or not. operator is found.
6. Computers use stack during interrupts and func- 2. After finding an operator remove operands
tion calls. The information regarding actual from stack, perform operation and store current
parameters, return values, return addresses and result on the stack.
machine status is stored in stack.
3. Repeat the above steps until the end of an
7. Stacks are used in depth first search of a graph. expression is reached.

5 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Example

Consider the following example to illustrate the evaluation of postfix, i.e., 8 2/3 + 4 8 * +

Stack
Token Top Action
[0] [1] [2]
8 8 [0] 8 is pushed onto stack
2 8 2 [1] 2 is pushed onto stack
[0] Evaluate 8/2 and push the result onto
/ 4
the stack.
3 4 3 [1] 3 is pushed onto stack
[0] Evaluate 4 + 3 and push the result
+ 7
onto the stack
4 7 4 [1] 4 is pushed onto the stack
8 7 4 8 [2] 8 is pushed onto the stack
[1] Evaluate 4 * 8, place result on the
* 7 32
stack.
[0] Evaluate 32 + 7, place result on the
+ 39
stack.

Q19. Transform the following infix expressions into their equivalent postfix expressions,

A+ B × (C + D) / F + D × E and (A+ B ^ D) / (E – F) + G

Answer : May/June-18, Q2 [OU]

(i) A + B × (C + D) / F + D × E

The given expression is A + B × (C + D) / F + D × E


I am complex but Worthy

Input Token Stack Output


A A
+ + A
B + AB
* +* AB
( +*( AB
C +*( ABC
+ +*(+ ABC
D +*(+ ABCD
) +*(+) ABCD
/ +/ ABCD + *
F – ABCD + * F / +
+ + ABCD + * F / +
D + ABCD + * F / + D
* +* ABCD + * F / + D
E +* ABCD + * F / + DE
– Empty ABCD + * F / + DE * +

∴ The postfix form for the given expression.

A + B * (C + D) / F + D * E is ABCD + * F / + DE * +.

Publishers and Distributors Pvt. Ltd. 6


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
(ii) (A + B ^ D) / (E – F) + G
The given expression is (A + B ^ D) / (E – F) + G

Input token Stack Output


( (
A ( A
+ (+ A
B (+ AB
^ (+^ AB
D (+^ ABD
) (+^) ABD
/ / ABD ^ +
( /( ABD ^ +
E /( ABD ^ + E
– /(– ABD ^ + E
F /(– ABD ^ + EF
) /(–) ABD ^ + EF
+ + ABD ^ + EF – /
G + ABD ^ + EF – / G
Empty ABD ^ + EF – /G +
∴ The postfix form for the given expression is,
(A + B ^ D) / (E – F) + G is ABD ^ + EF – /G +
Q20. Explain about reversing a string.
Answer : Nov./Dec.-17, Q1 [MGU]

Reversing a String using a Stack


The stack concept is the best and efficient way to reverse a string that is in sequential order. The LIFO (Last
in First Out) property of stack ensures string reversal. Each of single character is pushed into the stack sequentially
until the end of string is reached. Then stack pops the top element repeatedly and displays each element, until the
stacks empty. With this the elements will be displayed in reverse order.
Example
Reversing the string ABCDEF using stack is given below,

Input Action Stack Display


ABCDEF Push A A ← top of the stack –
BCDEF Push B AB ← top of the stack –
CDEF Push C ABC ← top of the stack –
DEF Push D ABCD ← top of the stack –
EF Push E ABCDE ← top of the stack –
F Push F ABCDEF ← top of the stack –
End Pop ‘F’ and display ABCDE ← top of the stack F
Pop ‘E’ and display ABCD ← top of the stack FE
Pop ‘D’ and display ABC ← top of the stack FED
Pop ‘C’ and display AB ← top of the stack FEDC
Pop ‘B’ and display A ← top of the stack FEDCB
Pop ‘A’ and display Stack is empty FEDCBA

7 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

P a r t- b E S S AY Q u e s t i o n s a n d A n s w e r s

1.1 Fundamental concepts

1.1.1 Introduction to Data Structures


Q21. Give a brief introduction on data structures.
Answer :
A data structure defines how a set of data elements are organized and how they are related with each other.
The fundamental concepts of data structures are as follows,
Data
Data denotes a part of information. The input, output and manipulation are the functions performed on the
data by the computer. The input provided can be number, string or combination of numbers and strings that is further
processed by the computer and displays the output to the user.
Data can be atomic and composite. The atomic data is the entity that is single and non decomposable as
selected by the user. The composite is the data that can be decomposed into several meaningful sub fields.
Data Type
Data type specifies the type of data that must be stored in a variable. Data types can be either built-in or user defined.
Built-in data types are those that are provided by the programming languages. For example int, float and
char are the built-in data types of C/C++. The programming languages also allow the users to define their own data
types. They are referred to as user-defined data types. For example class, structure and union are the user-defined
data types of C++.
Data Object
An object that contains the data values that are to be used later is called data object. It can be characterized
by a set of attributes, variables, constants or files defined by the programmer.
Data Structure
Data structure depicts the data and the representation of the data objects. It is a collection of both atomic
and composite data types or data structure along with set of associations or relationships.
Abstract Data Type
Data abstract separates the logical properties of the data from the presentation of data. Procedural abstraction
separates the logical properties of data from implementation. Abstract Data Type (ADT) is the combination of both
procedural and data abstraction.
1.1.2 Types of Data Structures
Q22. Briefly describe about the various types of data structure.
Answer : Nov./Dec.-17,Q9(a)(i) [OU]

Data Structure
Data structure can be defined as a way of organizing the data in the memory. Here, data Remember me
denotes a set of data elements and set of operations performed on it. Data structures are independent with concept
from their implementation and need some programming language to implement it.
Types of Data Structures
The various types of data structures are as follows,
1. Primitive and Non-primitive Data Structures
The data structure which specifies a set of primitive elements that do not contain any other sub elements is
called primitive data structure. The primary data types, integers and characters are the examples of these data structure.
The data structure which specifies derived elements is known as non-primitive data structures. The examples
of this data structure are structure, array and class, which contain different types of data elements and function to
operate on them.

Publishers and Distributors Pvt. Ltd. 8


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
2. Linear and Non-linear Data Structures 5. Sequential Access and Direct Access Data
Structures
Linear data structure is a data structure which
contains the elements in sequential manner. Each element A data structure is called as sequential access data
is linked to a unique predecessor and unique successor. structure if the data is accessed sequentially. Inorder to
These data structures can be represented using linked
access the nth element it need to access the elements from
lists (through pointers or links) or arrays (sequential
organization). 1st to nth element sequentially. A linked list is an example
Data Structure of the sequential access data structure.
A data structure is called as direct access data
structure if data elements are accessed directly, without
Linear Non-linear accessing previous or next elements of it. An array is an
example of the direct access data structure.
Linked Sequential Hierarchical
Relationship
Network
Relationship
1.1.3 Introduction to Algorithm
Organization Organization
Ex: Linked lists Ex: Arrays Ex: Trees Ex: Graphs Q23. Define algorithm. Give the steps for
Non-linear data structure is a data structure in algorithm development.
which the elements are not organized in any sequence. Answer : Model Paper-I, Q13(a)

These are used to represent hierarchical relationship or Algorithm


network relationship among the elements. Examples An algorithm can be defined as a step-by-step
of this data structure includes trees and graphs. Each procedure for solving a problem. It is very useful for
element in a non-linear data structures can contain finding the right answer to a problem by breaking the
multiple predecessors as well as multiple successors. problem into simple cases.
Steps for Algorithm Development
3. Static and Dynamic Data Structures
The steps to be followed while developing an
A data structure that is created before the algorithm are,
execution of a program is called static data structure. 1. Initially, understand the problem
Array is an example of static data structures. The names 2. Then, identify the expected output for the
of static data structure variables are user-defined. problem.
A data structure is said to be dynamic data 3. Identify the necessary input for the problem.
structure if it is created at run-time. The names of 4. Develop a logic that produces the expected output
the variables are not always user-defined. These data from the selected input.
structures grow and shrink dynamically. Non-linear data 5. Finally, test the algorithm with various sets of
structures such as trees and graphs can be implemented input.
as dynamic data structures. Characteristics of Algorithm
4. Persistent and Ephemeral Data Structures An algorithm must possess the following
characteristics,
The operations that are performed on a data in
1. Finiteness
the data structure may modify the data. The data which
2. Definiteness
is saved before the operations is called as the previous
version and the data after processing is called recent 3. Effectiveness
version. A persistent data structure is the data structure 4. Generality
that allows to perform operations on both the previous 5. Input/Output.
version and the updated version (recent version). It is said 1. Finiteness
to be partially persistent, when it accesses any version of An algorithm should terminate in a finite number
data, but updates the most recent one. It is said to be fully of steps.
persistent when it can access and update any version. 2. Definiteness
A ephemeral data structure is a data structure Each step of an algorithm must be precisely
that allows operations to be performed only on the stated.
most recent version. The data structures in conventional 3. Effectiveness
imperative language are the examples of ephemeral data Each step must be effective so that, it can be
structures because insertion of new data elements leads easily converted into program statement and can
to a new list and the old list will be lost. be performed exactly in a finite amount of time.

9 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
4. Generality 2. Pseudocode
The algorithm should be completed in itself, so Pseudocode is a way of describing general
that it can be used to solve all problems of a given structure of program in simple English language.
type for any input data. The word pseudo means imitation and code
5. Input/Output means instructions written in some programming
Each algorithm must take zero, one or more language. Pseudocode describes the complete
quantities as input data and yield one or more logic of some program so that implementation
output values. becomes easy. It does not use any syntax or
An algorithm can be written in English like symbols. It uses only English-like statements.
sentences or in any standard representations. Sometimes, 3. Flowchart
algorithm written in English like language is called Flowchart is a diagrammatic representation of
Pseudocode. an algorithm. It is built using different types
Example of boxes and symbols. The operation to be
performed is written in the box. All symbols are
Algorithm to find the average of three numbers,
interconnected by arrows to indicate the flow of
Step-1: Begin
information and processing.
Step-2: Read three numbers a, b and c Example
Step-3: Compute the sum of a, b and c //Flowchart to find the sum of first 50 natural numbers.
Step-4: Divide the sum by 3
Start
Step-5: Store the result in variable d
Step-6: Print the value of d Sum = 0

Step-7: End.
Num = 0
Q24. Write an algorithm to check prime
number. Num = Num + 1
Answer :
The algorithm to check prime number is as given Sum = Sum + Num

below,
Step1: Begin Is
Num = 50
Step2: Declare variables num, divisor, i ?

Step3: Initialize divisor to 1


Print sum
Step4: Initialize i to 2
Step5: Read num Stop
Step6: Repeat the following two steps until i < (num/2)
(a) If remainder of num/i = 0 4. Nassi-schneiderman
set divisor to 0 Nassi-schneiderman is the representation based
Go to step 8. on graphics. It makes use of the symbols and the
(b) Increment i to 1 languages in order to represent the decisions,
Step7: If divisor = 0 actions and sequence.
Display num is not a prime number.
1.1.4 Pseudo-code, Flowchart
else
Display num is a prime number. Q26. Explain in detail about how an algorithm
Step6: End. can be represented as pseudocode.
Q25. What are the various ways of stating Model Paper-II, Q13

algorithms. OR
Answer : Explain the concept of subalgorithms.
The four different ways of stating algorithms are Write an algorithm to compute the
as follows, following using a subalgorithm:
1. Step-form P = n! / (n – r)!
Step form consists of the statements written (Refer Only Topic: Sub-algorithms)
sequentially. These statements are written in Answer : June/July-19, Q9(a) [OU]
English language that represents a procedure
Pseudocode
used in order to solve a problem. Each statement
solves a part of the problem. All the statements For answer refer Unit-I, Page No. 10, Q.No. 25,
together solve the complete problem. Topic: Pseudocode.

Publishers and Distributors Pvt. Ltd. 10


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
“Pseudocode” represents the code required for Step-4: return –1
an algorithm in English. It is the most commonly used Step-5: Stop.
mechanism to represent algorithm pseudocode consists
The above algorithm searches for k element in an
of English as well as computer language structure code.
array Arr.
The structure code represents the syntax constructs of a
specific language with slight modifications. 3. Pre and Post Conditions
Pseudocode Notations Pre condition defines the pre-requirements
Pseudocode notations are used to give a complete needed by the parameters. For some of the programs,
description of solution for a particular problem. For pre-conditions are not required in such case, pre
this purpose algorithm header is loaded with pre-post condition is defined as nothing.
conditions, return statements, statement numbers, If a program contains several input parameters
variables and sub algorithms. These are the pseudocode then precondition should be mentioned for each of them.
notations used by the user to easily get the information An example of pre condition is as follows,
related to the variable and purpose at one instance. Pre array Arr to be sorted
1. Algorithm Header
The post condition defines the status of the output
The header is used to know the information about
parameters along with the actions that are performed.
an algorithm. It consists of the name of an algorithm, the
An example of post condition is as follows,
parameters and the pre and post conditions. The header
information should be completed and clear to the user in Post Sorted array Arr
order to understand the algorithm. Consider the below 4. Return Statement
algorithm, Return statement is used to identify the returned value.
Algorithm sort (reF Arr <Integer>, value x <Integer>) Return Loc
Step-1: Start
5. Statement Numbers
Step-2: If (x < 1) go to step 5
Step-3: k = x – 1 Statement numbers are the numbers assigned to
Step-4: for i = 1 to k do the statement in an algorithm sequentially. They identify
the statements easily and uniquely. The numbering
for j = i + 1 to x do
is done to statements such as iteration statement,
begin
conditional and unconditional jump statements. The
if (Arr(i)>Arr(j)) statements with in the iterative statements can be
then numbered by using the decimal number, roman number
begin or alphabets.
Temp = Arr(i) Consider the below example,
Arr(i) = Arr(j)
4. for i = 1 to n do
Arr(j) = Temp
end begin
endif 4.1. if(Arr(i) = k)
end then
Step-5: Stop 4.2 return;
The purpose of the above algorithm is to sort end if
array Arr of size x.
2. Purpose end
The purpose defines the main objective of the 6. Variables
algorithm. It gives a brief description about the algorithm Variables are the names assigned to the storage
processing. Consider the below algorithm. location. All the variables used in an algorithm need
Algorithm search (ref Arr <Integer> val k <Integer>) not be defined, variable names must be meaningful so
Step-1: Start that the context of data will be understood easily. Some
Step-2: Arr is an integer array and k is the thumb rules of it are as follows,
element to be searched (i) It would be better to use the descriptive names
Step-3: for i = 1 to n do rather than single characters. Generally, i, j, k are
begin used to name the index variables of loops, arrays
if (Arr(i) = k) etc.
then (ii) It is better to ignore the usage of short forms of
return i; variable names and generic names.
end if (iii) Variable names should indicate even the data type of
end if.

11 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
7. Statement Constructs
The statement constructs are used in developing algorithms. There are three types of statement constructs.
They are as follows,
(i) Sequence Statement Construct
An algorithm is made up of sequence of statements.
Example
1. Begin
2. Read r
3. A = 2 * 3.14 * r * r
4. Print A
5. Stop.
(ii) Decision or Selection Constructs
Sometimes execution of a set of instructions depends upon certain condition. If the condition is true then the
statements will be executed, otherwise, some other statements will be executed. This is referred as selection
or decision construct:
Example
1. Begin
2. read n1 and n2
3. if n1 > n2
then
print n1 is biggest
else
print n2 is biggest
endif
4. end.
(iii) Repetitive Statement Constructs
A set of instructions need to be executed repeatedly in certain situations.
Example
Algorithm sum
1. Begin
2. read n
3. initialize s and index s = 0 and index = 1
4. while index < = n do
s = s + index
//set of instructions
index = index ++
end while
5. return
6. end.
8. Sub-algorithms
Sub-algorithm is a small and effective part of the algorithm. A solution of a problem is divided into various
modules. This will break the algorithm to various sub algorithms. These sub-algorithms are called by different
names in programming language such as functions, procedure, etc.
Example
Algorithm for P = n!/(n – r)
Given expression is,
P = n!/(n – r)!

Publishers and Distributors Pvt. Ltd. 12


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Algorithm to compute the above expression is as follows,
1. Begin
2. Read n and r
3. Initialize the variable
(a) x = FACT (n)
(b) y = FACT (n – r)
x
4. P= y
5. Print P
6. Stop.
In the above algorithm, there is one unit called ‘FACT’ that has its own algorithm.
Sub-algorithm FACT
1. Read n
2. Let P = 1
3. while (n not equal to 1) do
3.1.P = P * n
3.2.n = n – 1
end while
4. Return P.
Q27. Define flowchart. Draw and explain the symbols used in flowchart.
Answer :
Flowchart
For answer refer Unit-I, Page No. 10, Q.No. 25, Topic: Flowchart.
Standard Symbols Used in Drawing Flowcharts

Name of Symbol Symbol Technical Name Purpose

Oval Terminal Start/stop/begin/end symbol

Parallelogram Input/Output Making data available for processing (input)


or recording of the processed Information
(output).
Rectangle Process Any processing to be performed. An
assignment operation normally represented
by this symbol.
Diamond Decision Decision or switching type of operations that
determines which of the alternative paths is
to be followed.

Circle Connector Used for connecting different parts of flow


chart.

Arrow Flow Joins two symbols and also represents


executions flow.
Bracket with Annotation Descriptive comments or explanations.
broken line
Double sided Predefined process Modules or subroutines given elsewhere.
rectangle

13 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Example Pseudo-code
The flowchart to find whether the sum of two Pseudo-code to compute the sum of the first N
numbers is odd or even is as follows, natural numbers.
1. int j, number, sum = 0
2. read number
3. j=0
4. do
j=j+1
sum = sum + j
till j < = number
5. Print sum.
Q29. Draw flowchart to calculate the roots of
a quadratic equation.
Answer : Model Paper-I, Q13(b)

Start

Read a, b, c

Q28. Define an algorithm. Write a flowchart and Yes Is


a pseudo-code to compute the sum of the a==0
first N natural numbers.
No
Answer : Nov./Dec.-17, Q9(a)(ii) [OU]
T=b*b–4*a*c
Algorithm
I am Simple and Easy
F o r a n s w e r r e f e r U n i t - I , d = sqrt(T)

Page No. 9, Q.No. 23, Topic: Algorithm.


Flowchart root1 = (–b + d)/(2 * a)

Flowchart to compute the sum of the first N


natural numbers. root2 = (–b – d)/(2 * a)

Pr int root1, root 2

Stop

Figure: Flowchart for Finding the Roots of the Given


Quadratic Equation
1.1.5 Analysis of Algorithms
Q30. Explain in detail about how Algorithms
are analyzed.
Answer : Nov./Dec.-19, Q7(a) [MGU]
N
Algorithms are developed by organizing the data.
There are number of ways to develop algorithms. For a
particular problem decision of selecting an appropriate
algorithm from many is that key job. One algorithm will
be compared with another to choose the best among them.
The key comparison factors would be the measure of
performance. This is done in terms of the below parameters.

Publishers and Distributors Pvt. Ltd. 14


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
(i) Time Complexity
The time complexity of the program is the amount of time taken by system to solve a problem.
Mathematically, it is expressed as,
T(P) = C + TP(I)
Where,
C is compile time and
TP(I) is the execution time.
Example
Consider an iterative function to sum a list of numbers.
float sum (float list[ ], int n)
{
float tsum = 0;
int i;
for(i = 0; i < n; i++)
tsum + = list[i];
reutrn tsum;
}
The time complexity of the function is shown in table below:

Statement Steps/execution (S) Frequency (F) Total-steps = S × F


float sum (float list[ ], int n) 0 0 0
{ 0 0 0
float tsum = 0; 1//This statement is executed 1 1
only 1 time
int i; 0 0 0
for (i = 0; i < n; i++) 1//for loop is executed 1 time n + 1 //takes n + 1 passes n+1
tsum + = list[i]; 1//executes 1 time n //takes n passes n
return tsum; 1//return statement executes 1 //take only 1 pass 1
only 1 time
} 0 0 0
2n+3
v Average Case
If an algorithm takes average time to solve a problem on the given input instance then this case is called
as the average case. The time complexity of an algorithm in such case is referred to as average time
complexity.
Example
Consider the example to find the first odd number from the given list.
0 2 4 7 8 1 3
As 7 is the first odd number in the array, the algorithm takes average time to search 7, since it is present in the
middle of list.
v Best Case
If an algorithm takes minimum time to solve the problem for the given input, then this case is called as
best case. The time complexity of algorithm in such a case is referred to as best case time complexity and
is expressed as O(1).
Example
Consider an example to find the first odd number from the list.
1 2 7 6 5 4
As 1, (the first odd number) occurs as the 1st position, the time and comparison taken to search the ele-
ment is minimum. Therefore, it is considered as the best case.

15 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
v Worst Case
If an algorithm takes maximum time to solve a problem for the given input, then this case is called as worst
case. The time complexity of algorithm in such case is known as worst case time complexity. Usually ex-
pressed as O(N), where N is size of input.
Example
Consider an example to find the first odd number from the list.
2 4 6 8 12 18 7
Since, 7 (the first odd number in the list) is the last element in the list. The number of comparison needed to
find element is 7. Hence, the time complexity is O(7). As it takes longer time to find the number, it is consid-
ered as a worst case.
(ii) Space Complexity
The space complexity of a program is the amount of memory space required to solve a problem.
Mathematically it is expressed as,
S(P) = C + SP(I)
Where,
C is the fixed space requirement
SP(I) is a variable space requirement.
Example
Consider recursive function for summing a list,
float rsum (float list[ ], int n)
{
if(n)
return rsum (list, n – 1) + list (n – 1);
}
The space complexity of the above function is computed in table below:
Type Name[ ] Number of Bytes
Parameter list[ ] 2 //since list is a parameter, it takes 2 bytes
Parameter n 2 //since n is a parameter, it takes 2 bytes
return address 2 //the return address i.e., last statement also
//takes 2 bytes
Total 6 //after summing up we get 6
\ S sum(I) = S sum(n)
= 6(n)
= 6n
Space complexity can be defined at runtime and compile time and it will be called as runtime space com-
plexity and compile time space complexity respectively.
Components of Space Complexity
The three components of space complexity are as follows:
1. Instruction Space / Code Space
The instruction space/code space holds the compiled version of program instruction. The minimum
amount of instruction space required depends on the three factors (the space used by compiler, the model
used in complier, the hardware platform).
2. Data Space
Data space holds all the static data such as constants and variables as well as dynamic data such as grow-
ing structures.
3. Environment Stack Space
Environment stack space stores the return address of a function. Thus, the execution can be resumed
from the point where the execution was halted.

Publishers and Distributors Pvt. Ltd. 16


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Q31. Write a short notes on Big-oh notation. Q32. Define ADT for the “Integer” and explain
all its functions and axioms in detail.
Answer :
Answer : Nov./Dec.-18, Q9(a) [OU]
Big-oh Notation ADT for the “Integer”
Big-oh notation is represented by symbol ‘O’. ADT Integer
It is a method that defines the upper bound of algo- Operations:
rithm’s running time. Using this notation, user can
Function zero( ): return int
calculate the longest time taken by algorithm to per-
form its computation. Function ifzero(int): return boolean
Function increment(int): return int
Mathematical Definition
Function add(int, int): return int
Consider f(n) and g(n) as two non-negative integers. Function equal(int, int): return boolean
A function f(n) is said to be equal to O(g(n)), if Axioms:
there exist a positive constant c and n such that, for: x, y ∈ integer
f(n) ≤ c.g(n) ∀ n, n ≥ no ifzero(zero( )) = True
Example ifzero(increment(zero( ))) = False
add(zero( ), x) = x
Let,
add (increment(x, y)) = increment(add(x, y))
f(n) = 3n + 2 and
equal(increment(x), increment(y))
g(n) = 4n = equal(x, y)
Substituting n = 1 End Integer
Functions
f(n) = 3n + 2
The functions used in the “Integer” ADT are as
f(1) = 3(1) + 2 follows,
=5 (i) zero( )
g(n) = 4(n) It doesn’t take any input, but it returns integer
value (i.e., zero) as output.
g(1) = 4(1)
(ii) ifzero(int)
=4 It takes an integer as input. It also checks whether
Since, f(n) > g(n). The above condition fails. this integer value is zero or not and then returns
boolean value (i.e., True or False) as output.
\ n = 1 does not satisfy the above condition.
(iii) increment(int)
Substituting n = 2 It takes an integer as input. It then, increments
f(n) = 3n + 2 this integer value by 1 and returns output which
is also an integer.
f(2) = 3(2) + 2
(iv) add(int, int)
=6+2
It takes two integers as input. It then adds both
=8 these integers and returns output which is also an
g(n) = 4n integer.
(v) equal(int, int)
g(2) = 4(2)
It takes two integers as input. It then compares
=8 these two integers values and returns a boolean
Since, f(n) = g(n). n = 2 satisfy the above condition, value (i.e., True or False) as output.
Axioms
\ 3n + 2 ≤ 4(n) ∀ n, n ≥ 2
The axioms used in the “Integer” ADT are as
[Where, c = 4, g(n) = n and n 0 = 2] follows,
Hence, (i) ifzero(zero) Þ True
f(n) = O(g(n)) In this axiom, the ifzero( ) function is applied on
zero( ) function. The zero( ) function generates
= O(n) integer 0 and the ifzero( ) function checks the
Therefore, the time complexity for f(n) = 3n + 2 integer value (i.e., 0) returned by zero( ) function
is O(n). and returns “True” as output.

17 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
(ii) ifzero(increment(zero( ))) Þ False Syntax
In this axiom, the zero( ) function returns 0 and it type array_name[size];
is incremented to ‘1’ by the increment( ) function.
Next, ifzero( ) function takes integer ‘1’ as input Where, ‘type’ is a data type
and returns False because the integer is not ‘0’. ‘array_name’ is the name of array and
(iii) add(zero( ), x) Þ x
‘size’ indicates number of values assigned to an array.
In this axiom, the zero( ) function returns 0 and next
it is added with another input ‘x’ i.e., (0 + x). Thus One-dimensional Arrays
add( ) function returns ‘x’ because 0 + x = x. One-dimensional array is a simple array in which
(iv) add(increment (x), y) Þ increment(add(x, y)) elements are stored in contiguous memory locations.
In this axiom, both the functions returns the same Array elements can be accessed using one subscript.
value. For instance, consider x = 1, y = 2 and Syntax
apply both the functions.
(a) add(increment(x), y) datatype array_name[size];
= add(increment(1), 2) Example
= add(2, 2) int xyz[10];
=4
Here, xyz is an array of 10 integers.
(b) increment(add(x, y))
= increment(add(1, 2)) This means, the computer reserves ten storage
locations in the memory as,
= increment(3)
=4 ……
Thus, both these functions returns the same value. xyz[0] xyz[1] xyz[2] xyz[3] …… xyz[n]
(v) equal(increment (x), increment(y)) Þ equal(x, y)
In this axiom, suppose if x and y values are equal When the values are entered, the array will assign
then the increment of x by 1 and increment of y these values to its corresponding element as shown
by 1 will also be equal. below,
For instance, consider x = 3, y = 3 xyz [0] = 5;
(a) equal(x, y) xyz [1] = 10;
= equal(3, 3)
xyz [2] = 12;
= True
xyz [3] = 13;
(b) equal(increment(x), increment(y))
= equal(increment(3), increment(3)) xyz [4] = 14;
= equal(4, 4) xyz [5] = 15;
= True. xyz [6] = 16;
1.2 Linear data structure using xyz [7] = 17;
arrays
xyz [8] = 18;
1.2.1 1-D Arrays, 2-D Arrays, N-D Arrays,
Memory Representation and Address xyz [9] = 19;
Calculation of 1-D, 2-D, N-D Arrays All these values will be stored in the following
Q33. Define array. Discuss about one- format.
dimensional arrays.
5 10 12 13 …… 19
Answer :
xyz[0] xyz[1] xyz[2] xyz[3] …… xyz[9]
Array
Array is a basic data type that stores similar Address of an element in one dimensional array
elements. It is capable of holding fixed values in is calculated using the below formulae.
contiguous memory locations. The general format of Address of a[i] = B + W + (i – LB).
an array is,
Here, B represents base address, i represents
a0 a1 a2 .. .. .. .. an subscript, W represents stages size of an element and LB
represents lower limit or lower bound of the subscript.

Publishers and Distributors Pvt. Ltd. 18


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Program void array::traverse_backward( )
// A simple C++ program to illustrate the concept of array {
#include<iostream> int i;
#include<iomanip> for(i=size–1;i>=0;i– –)
#include<conio.h> cout<<a[i]<< “ ”;
using namespace std; cout<<endl;
class array }
{ int array::search(int elem)
private: {
int max,a[50],size; int i;
public: for(i=0;i<size–1;i++)
array( ) {
{ if(elem==a[i])
max=20; return(i);
size=0; }
} return(–1);
void read( ); }
void show( ); void array::insert(int location,int elem)
{
void traverse_backward( );
int i;
void insert(int location, int elem);
if(size>=max)
void delet (int location);
{
int search(int elem);
cout<< “overflow”;
};
return;
void array::read( )
}
{
for(i=size–1;i>=location–1;i – –)
int i,n;
{
cout<<“Enter the size of array:”;
a[i+1]=a[i];
cin>>n;
}
if(n>max)
a[location–1]=elem;
{
size=size+1;
cout<<“Array of this size cannot be created”;
}
cout<< “Maximum size is:”<<max; void array::delet(int location)
return; {
} int i;
else for(i=location;i<size;i++)
{ {
for(i=0;i<n;i++) a[i–1]=a[i];
{ }
cin>>a[i]; a[size–1]=0;
} size=size–1;
size=n; }
} int main( )
} {
void array::show( ) array a;
{ a.read( );
int i; cout<< “\nThe elements of the array are:\n”;
for(i=0;i<size;i++) a.show( );
cout<<a[i]<<“ ”; cout<< “\nThe elements of the array
cout<<endl; after traversing backward are:\n”;
} a.traverse_backward( );

19 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
a.insert(3,66); // Inserting 66 at position-3 void delet (int location);
cout<< “\nThe elements of the array after };
insertion are:\n”; void array::read( )
a.show( ); {
cout<<endl; int i,n;
a.delet(3); //Deleting an element at position-3 cout<<“Enter the size of array:”;
cout<< “\nThe elements of the array after cin>>n;
deletion are:\n”; if(n>max)
a.show( ); {
cout<<endl; cout<<“Array of this size cannot be created”;
cout<< “The result after searching for cout<<“Maximum size is”<<max;
element 66 is:\n”<<a.search(66)
return;
<<endl; // Searching for element 66
}
cout<< “\nThe search element is found
else
at location:\n”<<a.search(3);
//Searching for elememt 3 {
return 0; cout<<“Enter the array elements:\n”;
} for(i=0;i<n;i++)
{
Output
cin>>a[i];
}
size=n;
}
}
void array::show( )
{
int i;
for(i=0;i<size;i++)
cout<<a[i]<<“\t”;
cout<<endl;
}
Q34. Write a C++ program to implement the void array::insert(int location,int elem)
following operations on Arrays. {
(i) To insert an element at a given position int i;
(ii) To delete an element at a given position. if(size>=max)
Answer : Nov./Dec.-18, Q9(b) [OU] {
Program cout<< “overflow”;
#include<iostream.h> return;
#include<iomanip.h> }
#include<conio.h> for(i=size–1;i>=location–1;i– –)
ple

class array {
Very Sim
ex
pl

{ a[i+1]=a[i];
m
Co

t
g n

bu
ki

private: }
o
Lo

int max,a[50],size; a[location–1]=elem;


public: size=size+1;
array( ) }
{ void array::delet(int location)
max=20; {
size=0; int i;
} for(i=location;i<size;i++)
void read( ); {
void show( ); a[i–1]=a[i];
void insert(int location, int elem); }

Publishers and Distributors Pvt. Ltd. 20


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
a[size–1]=0; Column 0 Column 1 Column 2
size=size–1;
}
Row 0 a[0][0]a ]a [0][1] a[0][2]
void main( )
{ Row 1 a[1][0]a ]a[1][1] a[1][2]
clrscr( );
Row 2 a[2][0]a ]a [2][1] a[2][2]
array a;
a.read( ); Row 3 a[3][0]a ]a[3][1] a[3][2]
cout <<“\n Display the array \n”;
Row 4 a[4][0]a ]a [4][1] a[4][2]
cout <<“\n Insertion operation \n”;
a.insert(3, 0); Declaration of Two-dimensional Arrays
a.show( ); The general format of declaring a two-dimensional
array is,
cout<<“\n Deletion operation \n”;
type array_name[row-size][column-size];
a.delet(3);
Where ‘type’ represents the data type of array
a.show( ); elements, ‘array_name’ is the name of the array,
getch( ); ‘row-size’ specifies the number of rows in the array
} and ‘column-size’ specifies number of columns in the
array. Both row-size and column-size must be integer
Output constants.
Examples
1. int xyz[2][5];
Here, ‘xyz’ is an array consisting of two rows with
each row consisting of 2 integer elements.
2. float a[5][5];
Here, a is an array consisting of 5 rows with each
row consisting of 5 floating point numbers.
Program
#include<iostream.h>
#include<conio.h>
Q35. What do you mean by two-dimensional int main( )
array? Write briefly about two-dimensional {
array declaration.
int p[2][2], q[2][2], r[2][2];
Answer : int i, j;
Two-dimensional Array clrscr( );
Two-dimensional arrays can be used when the cout<<“Enter the elements of first matrix:”
data must be stored in the form of a matrix. It is an array <<endl;
having two dimensions.
for(i = 0; i < 2; i++)
Syntax
for(j = 0; j < 2; j++)
datatype array_name [row size] [column size];
cin>>p[i][j];
Example
cout<<“Enter the elements of second
int a[5][3]; matrix”<<endl;
Above declaration represents a two-dimensional for (i = 0; i < 2; i++)
array consisting of 5 rows and 3 columns. So, the total for (j = 0; j < 2; j++)
number of elements which can be stored in this array are
5 × 3 i.e., 15. cin>>q[i][j];
The representation of two-dimensional array of /* Adding two matrices p and q */
size 5 × 3 in the memory is shown below, for(i = 0; i < 2; i++)

21 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
{ 0 1 j

.
.
.
.

.
.
.
.
for (j = 0; j < 2; j++) 0
{
r[i][j] = p[i][j] + q[i][j]; 1
.
.
} .
.
}
i xyz[i][j]]
xyz[i]
cout<<“\n the addition of two matrices is \n”; .
.
for(i = 0; i < 2; i++) .
.
{
The number of elements in a two-dimensional
cout<<“\n”;
array is given as,
for (j = 0; j < 2; j++)
(Upper_bound – Lower_bound + 1) * Number of columns
{
(or)
cout<<r[i] [j];
Number of rows * Number of columns.
cout<<“ ”;
(ii) Storage Representation of Two-dimensionalArrays
}
} Two-dimensional arrays logically consist of rows
and columns but when it is stored in memory, no facility
getch( );
for two-dimensional storage is available. The memory is
return 0; linear. Hence, the actual storage differs from our matrix
} representation. Two major types of representations can
Output be used for two-dimensional arrays,
(a) Row major representation
(b) Column major representation.
(a) Row Major Representation
In row major representation, the elements of first
row are stored in contiguous memory locations followed
by elements of second row and so on.
Example
Consider an array,
int a[3][4];
0 1 2 3
0 1 2 3 4
1 5 6 7 8
Q36. Explain briefly about,
2 9 10 11 12
(i) Referencing elements of two-
dimensional array Figure (a): Logical View of a[3][4]
(ii) Storage representation of two- Its actual row major representation is,
dimensional arrays. 0 1 500
OR 1 2 502
row 0
Explain row-major and column-major 2 3 504
memory representations for 2-D arrays. 3 4 506
(Refer Only Topic: Storage Representation 0 5 508
of Two-dimensional Arrays)
1 6 510
Answer : May/June-18, Q9(a)(i) [OU] row 1
2 7 512
(i) Referencing Elements of Two-dimensional Array 3 8 514
The elements of an array can be referenced using 0 9 516
two indices, one for obtaining row numbers and another
1 10 518
for obtaining column numbers. row 2
2 11 520
Example
3 12 522
xyz[i][j] is used to access ith row and jth column
element. Figure (b): Physical View of Array a[3][4]

Publishers and Distributors Pvt. Ltd. 22


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Here, 500 is the base address of the array and The logical view of A[3][4] is given below,
each element is stored at a distance of 2 bytes because 0 1 2 3
each integer element requires two bytes of storage. 0 1 2 3 4
Accessing Address of an Array Element 1 5 6 7 8
If the base address of an array is known, then it 2 9 10 11 12
is possible to access any element in that array.
The row-major representation of an array is as follows,
In an array a[m][n], the address of an element a[i]
0 1 1050
[j] is given as, 1 2 1052
Row 0
Base address + (i × n + j) × Size of array element. 2 3 1054
3 4 1056
For the array a[3][4], address of int a[1][3] is 500
0 5 1058
+ (1× 4 + 3) × 2 = 514 where n = 4 which can be verified
1 6 1060
from figure (b). Row 1
2 7 1062
(b) Column Major Representation 3 8 1064
0 9 1066
In column major representation, the elements of
1 10 1068
first column are stored in contiguous memory locations Row 2
2 11 1070
followed by elements of second row and so on. 3 12 1072
The column major representation for the array
Here, 1050 is the base address of the array and
given in figure (c) is given below.
each element is stored at a distance of 2 bytes because
0 1 500 each integer element requires two bytes of storage.
Column 1 1 5 502 The address of an element for an array A[3][4] is
2 9 504 calculated using the formula,
0 2 506 Base address + (i × n + j) × size of array element
Column 2 1 6 508 Given array is A[3][4] in the form of A[m][n] and the
address value of an array is A[2][3] in the form of A[i][j].
2 10 510
Address of an element = 1050 + (2 × 4 + 3) × 2
0 3 512
= 1050 + (8 + 3) × 2
Column 3 1 7 514 = 1050 + (11) × 2 = 1072
2 11 516 ∴ The address of the element A[2][3] is ‘1072’.
0 4 518 The column-major representation of an array is
Column 4 1 8 520 as follows,
2 12 522 0 1 1050
Column 1 1 5 1052
Figure (c) 2 9 1054
Accessing Address of an Array Element 0 2 1056
In an array a[m][n] stored using column major Column 2 1 6 1058
order, the address of a[i][j] is given as, Base address + 2 10 1060
(i + j × m) × Size of array element. 0 3 1062
Column 3 1 7 1064
Example
2 11 1066
For the array a[3][4], address of a[2][3] is, 0 1068
4
500 + (2 + 3 × 3) ×2 = 522 Column 4 1 8 1070
Q37. Consider an integer array, int A[3][4] in 2 12 1072
C++. If the base address is 1050, find the
Address of an element for an array A[3][4] is
address of the element A[2][3] with row-
calculated by using the formula,
major and column-major representations
Base address + (i + j × m) × size of the array element.
of the array.
Address of an element A[2][3] = 1050 + (2 + 3 × 3) × 2
Answer : May/June-18, Q9(a)(ii) [OU]
= 1050 + (11) × 2
Consider an integer array, int A[3][4]; = 1050 + 22 = 1072.
Given that the base address is 1050 for an array. ∴ The address of an element A[2][3] is ‘1072’.

23 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Q38. Write short notes on the following: printf(“Enter the number of rows of the matrices:”);
(i) Memory representation and address scanf(“%d %d”, &rows, &cols);
calculation of 1-D, 2-D arrays printf(“\nEnter elements of 1st matrix:\n”);
(ii) Different types of data structures. for (i = 0; i < rows; ++i)
Nov./Dec.-17, Q5(a) [MGU] for (j = 0; j < cols; ++j)
OR {
scanf(“%d”, &m1[i][j]);
Explain memory representation and ad-
dress calculation of 1-D and 2-D arrays. }
printf(“Enter elements of 2nd matrix:\n”);
(Refer Only Topic: Memory Representation and
Address Calculation of 1-D, 2-D Arrays) for (i = 0; i < rows; ++i)
for (j = 0; j < cols; ++j)
Answer : Nov./Dec.-19, Q9(a)(ii) [OU]
Don’t Think
{
(i) Memory Representation I am Complex scanf(“%d”, &m2[i][j]);
and Address Calculation
}
of 1-D, 2-D Arrays
for (i = 0; i < rows; ++i)
v 1-D Array
for (j = 0; j < cols; ++j)
For answer refer Unit-I, {
Page No. 18, Q.No. 33, Topic: One-dimensional
Arrays. sum[i][j] = m1[i][j] + m2[i][j];
v 2-D Array }
For answer refer Unit-I, Page No. 22, Q.No. 36(ii). printf(“\nSum of two matrices: \n”);
(ii) Types of Data Structures for (i = 0; i < rows; ++i)
For answer refer Unit-I, Page No. 8, Q.No. 22. for (j = 0; j < cols; ++j)
Q39. Write a short notes on n-dimensional {
array. printf(“%d”, sum[i][j]);
Answer : if (j == cols – 1)
The n-dimensional array can be represented only {
by making use of ‘n’ indices (i.e., i1, i2, i3 ..... in). printf(“\n”);
Consider xk be the elements present in kth dimension }
whose range of index for ik ranges in between lk and uk }
wherein the value of ‘k’ lies in between ‘1’ and ‘n’.
return 0;
The n-dimensional array can be represented in
}
memory using row-major order and column-major order
by the following formulae. Output
For row-major order,
Address(bi1, i2, i3 ..... in) = (in – ln) xn – 1 xn – 2 ......
x1 + (in – 1 – ln – 1 ) xn – 2 xn – 3 ..... x1 + ........ (i1 – l1)
For column-major order,
Address(bi1, i2, ..... in) = (i1 – l1) x2 x3 ...... xn + (i2 – l2 )
x3 x4 ..... xn + ........ (in – ln)
If the array 3 dimensional array then N3 = 3.
0,0,0 0,1,0 0,2,0 0,0,1 0,1,1 0,2,1 0,0,2 0,1,2 0,2,2
1,0,0 1,1,0 1,2,0 1,0,1 1,1,1 1,2,1 1,0,2 1,1,2 1,2,2
2,0,0 2,1,0 2,2,0 2,0,1 2,1,1 2,2,1 2,0,2 2,1,2 2,2,2
Q40. What is an array? Explain
Program about different types of ar-
#include <stdio.h> rays. (Model Paper-III, Q13 |
int main() Answer : May-18, Q5(a) [MGU]) Remember me
with concept
{ Array
int rows, cols, m1[100][100], m2[100][100], For answer refer Unit-I, Page No. 18, Q.No. 33,
sum[100][100], i, j; Topic: Array.

Publishers and Distributors Pvt. Ltd. 24


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Types of Arrays The examples of ordered list are as follows,
The different types of arrays in C are as follows, 1. Days of a Week
1. One-dimensional arrays A week consists of seven days (Sunday,
2. Two-dimensional arrays Monday Tuesday, Wednesday, Thursday, Friday,
Saturday). It can be represented as an ordered list
3. n-dimensional arrays. as shown below,
1. One-dimensional Arrays Days in a week (D) = {Sunday, Monday, Tuesday,
For answer refer Unit-I, Page No. 18, Q.No. 33, Wednesday, Thursday, Friday, Saturday}
Topic: One-dimensional Arrays. 2. Prime Numbers upto 10
2. Two-dimensional Arrays The prime numbers from 1 to 10 are 2, 3, 5, 7 and
For answer refer Unit-I, Page No. 21, Q.No. 35. this can be represented as follows,
3. n-dimensional Arrays Prime numbers less than 10 (P) = {2, 3, 5, 7}.
For answer refer Unit-I, Page No. 24, Q.No. 39. 1.2.3 String Manipulation
1.2.2 Concept of Ordered List Q42. Explain about string manipulation in C++.
Q41. Discuss the concept of ordered list. Answer :
Answer : String Manipulation Using Array
Ordered List Manipulating the strings through the operations
such as comparison, concatenation etc is referred as
Ordered list can be defined as a list that consists
string manipulation. A string can be stored in one-
of linear elements which follow some specific sequence.
dimensional array as shown below,
The elements are associated with each other based on
a specific condition. It is the most commonly used data char str[12] = “Manipulate”
object. The best and efficient data structure to represent 0 1 2 3 4 5 6 7 8 9 10 11
the ordered list is an array. Array stores the elements in str = M A N I P U L A T E \0 –
the sequential order. The array index starts from 0 (zero).
The different operations that are performed on a
Assume that L to be the ordered list,
string are as follows,
L = {x0, x1, x2, ... , xn–2, xn–1} 1. Computing String Length
Here, L contains n elements ranging from x0, to The length of string ie., number of characters of
xn–1. If L is stored in the form of array it is represented a string is computed.
as L[n], The ith element can be stored at ith location in the Function Definition
array. As the array index starts from zero, the element int string : : len( )
x0 is stored at 0th location, the element x1 stored at 1st
{
location, and so on, the elements xn–2 and xn–1 are stored
int len = 0, i;
at (n – 2)th and (n – 1)th locations respectively. L can be
for(i = 0; s[i]! = ‘\0’;i = ++)
represented as an array as shown below,
len++;
L[0] L[1] L[2] .......... L[n – 2] L[n – 1] return len;
x0 x1 x2 .......... xn–2 xn–1 }
2. String Concatenation
Operations
Two strings are merged and stored in a single string.
The basic operations that can be performed on an Function Definition
ordered list are as follows,
void string : : concatenate(string A)
1. Inserting an element at ith location. {
2. Accessing an element from ith location in list. int len_B,i,j;
3. Deletion of an element from the ith position. for(i = 0; s[i]! = ‘\0’, i++) //loop terminates
4. Updation of an element at the ith location. len-B = i;
5. List traversal from left to right or from right to left. for(i = len_B, j = 0; A.S[j]! = ‘\0’; j++, i++)
{
6. Computing length of the list.
s[i] = A.S[j];
The above mentioned operations can be
}
effectively applied on arrays. By using a controlled
subscript variable, it is easy to traverse the list in any s[i] = ‘\0’;
direction. }

25 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
3. String Copying R A C E C A R
The characters of one string are copied into
another string sequentially.
Function Definition
string string : : copy( )
{ There are two approaches to check whether a
string str; string is palindrome or not. One approach is to find the
for(int i = 0; s[i]! = ‘\0’; i++) reverse of the given string and then compare it with the
str.s[i] = s[i]; original string. If the both strings are equal then the string
str.s[i] = ‘\0’; is said to be palindrome. It needs additional data structure
return str; for storing the reversed string. The second approach is
} to match the first character with the last character if it is
4. Reversing a String found to be same then the second character is matched
All the characters in the given string will be with the last second character. This process is continued
displayed in the reverse order. until the middle element is reached. If all the characters
Function Definition of first string match with the second string then it is said
string string : : revstring( ) to be palindrome.
{
Code for the palindrome_check operation is as
int l = 0;
follows,
char temp;
for(l = 0; s[l]! = ‘\0’; l ++); int string : : palindrome( )
for(int i = 0, j = l – 1; i! = j; i++, j – –) {
{ int i,j,len, f = 0, k;
temp = s[i]; for(len = 0; s[len]! = ‘\0’; len ++);
s[i] = s[j];
s[j] = temp; len – –;
} k = len/2
} for (i = 0; j = len; i < = k; i++, j++)
5. String Comparison {
One string is compared with another string for
if (s[i] = = s[j])
equality.
Function Definition {
int string : : strcmpare(string s1, string s2) f = 1;
{ continue;
if(s1.len( )! = s2.len( ))
}
return 0;
while (s1.s[i] = = s2.s[i] && s1.s[i]! = else
‘\0’&& s2.s[i]! = ‘\0’) {
{ f = 0;
++i;
break;
if(s1.s[i] = = ‘\0’ && s2.s[i] = = ‘\0’)
return 1; }
else }
return 0; if(f = = 1)
} return 0;
}
else
Q43. Write in brief about,
return 1;
(i) Palindrome check
}
(ii) Substring check.
(ii) Substring Check
Answer :
Substring check is to find the occurrence of one
(i) Palindrome Check string in another string. Consider the below string
Palindrome check is one of the string manipulation s1 = ‘USHA’
operations. Palindrome string is a string that contains
s2 = ‘US’ or ‘SHA’ or ‘SH’ and so on
same characters when read in both the forward and
backward directions. An example of palindrome is Here, s1 is checked to determine whether it
“RACE CAR”. Consider the below string, contains s1 in it as substring.

Publishers and Distributors Pvt. Ltd. 26


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Code for the substring check string operation is as Answer :
follows, Arrays
int string : : ss(string s2) For answer refer Unit-I, Page No. 18, Q.No. 33,
{ Topic: Array.
int f = 0, j = 0; Advantages of Arrays
for(int i = 0; s1.s[i]! = ‘\0’ || s2.s[i]! = ‘\0’; i++) 1. They are used to store the fixed size data. They
{ also support the high frequency of data retrievals.
if(s1.s[i] = = s2.s[j]) 2. They allow data to be accessed randomly and
{ directly in O(1) time.
j++; 3. They are used to represent the data structures like
f = 1; stacks, queues and the complex data structures
} like heaps and hash tables.
else 4. They are used in applications like searching,
{ sorting hash tables and matrix operations.
j=0 5. They consume only the required amount of
f = 0; memory for storing the data. Hence, it is the most
} compact data structure among all data structures.
} 6. They are the most preferable data structures where direct
if(f = = 1) mapping is required between the elements and their
return 1; positions. Ordered list is an example for this approach.
else Disadvantages of Arrays
return 0; 1. The size of an array cannot be changed during run-
} time because it supports static memory management.
2. They can be declared with some arbitrary
1.2.4 Pros and Cons of Arrays maximum size to avoid the problem of array
Q44. L i s t o u t t h e c h a r a c t e r i s t i c s a n d being static. This leads to below problems.
applications of arrays. (a) User cannot exceed the given limit even in
Answer : required cases.
Characteristics of Array (b) For small computations, the program uses
less memory and the remaining reserved
1. Array is the simplest kind of data structure.
memory will be wasted. This leads to
2. It is relatively easy to create, understand and wastage and poor utilization of memory.
implement arrays. 3. They lead to certain problems in some programming
3. It can directly access any element. However, languages since they are allocated statically.
modifications done to one element does not effect 4. They are not suitable for applications that
the other. involve frequent insertions and deletions. These
4. It posses the capability of linking data together, operations need data movement in the arrays.
especially with multiple dimensions. 5. They allow a non existent element to be
5. Every array element can be accessed at constant time. referenced through an index that is out of valid
6. It can store more number of values. range. This is called exceeding the array bounds.
Application of Arrays This feature makes the program to work with
1. They are used for storing the two dimensional incorrect data and even lead to system crash.
data and multi-dimensional data.
2. They are used to implement the sorting, searching
1.3 Stacks
and indexing. 1.3.1 Concept, Primitive Operations
3. They are used to represent the complex data
structures such as hash tables and heaps. They Q46. Explain the stack operations with program
can also help in implementing stacks and queues. codes and examples. May/June-18, Q9(b) [OU]
4. They are used to represent the sparse matrices. They OR
store associative arrays with the integer elements. Define stack. Give a brief
introduction on stack.
Q45. What is an array and explain its advantages
Answer : Nov./Dec.-19, Q7(b) [MGU]
and disadvantages? Nov./Dec.-19, Q9(a)(i) [OU]
Stack I
am
OR tou
gh but important
A stack is a linear data structure
List out the pros and cons of arrays. that stores a set of elements in a sequential manner. In
(Refer Only Topics: Advantages of Arrays, stack, new elements can be inserted and the existing
Disadvantages of Arrays) elements are deleted to/from only single end called TOP.

27 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Stacks is an ordered collection of homogeneous Answer : Nov./Dec.-17, Q6(b) [MGU]
items that follow LIFO(Last in First Out) procedure in Operations Performed on Stack
which, the element that is inserted last is deleted first. The The three basic operations that are performed on
various operations performed on stacks are as follows, stack are as follows,
1. Push (i) PUSH operation
2. Pop.
I am a

(ii) POP operation Repeated


Question

1. Push (iii) STATUS operation.


The method of inserting an element onto a stack is (i) PUSH Operation
called “PUSH” operation. It adds a new element This operation helps in inserting an ITEM
onto the top of stack. (element) onto the stack. This operation can be
2. Pop implemented in two ways. They are,
The method of deleting an element from a stack 1. By using array
is called “POP” operation. It deletes the top most 2. By using linked list.
element present on the stack. 1. Implementing PUSH Operation Using Array
The position where the above two operations are The algorithm for implementing PUSH operation
performed is called “TOP”. The number of elements using array is as follows,
which are present in stack are called “ITEMS”. The Algorithm PUSH_USING_ARRAY
representation of stack is shown below, Input
TOP ITEM(new element) that should be pushed on the
stack.
Data Structure
An array M containing a pointer called TOP.
Insertion(Push) 10 Deletion(POP)
Output
20
The new ITEM on the Top of stack.
30 Step-1
40 Check the size of stack using following operation.
If TOP ≥ size_of_stack then
50 Print “No item can be inserted as stack is Full”.
60 Bottom Step-2
Figure: Representation of Stack GO TO ELSE.
Step-3
Examples
Increment TOP by 1
The concept of stack can be used in the following
areas, TOP = TOP + 1
1. For shunting trains in railway yard. Step-4
2. For the purpose of shipment in a cargo and Assign ITEM to M[TOP]
3. For arranging plates in a tray. M[TOP] = ITEM.
Program Step-5
For answer refer Unit-I, Page No. 33, Q.No. 51. End If
Step-6
Q47. Explain the primitive operations on
Stop
STACKS with arrays. Nov./Dec.-18, Q5(a) [MGU] 2. Implementing PUSH Operation Using Linked
OR List
Explain about operations on stack. The algorithm for implementing PUSH operation
May-18, Q5(b)(i) [MGU] using linked list is as follows,
OR Algorithm PUSH_USING_Linked List
Explain the primitive operations of STACK. Input
ITEM(new item) that should be inserted on stack.
(Model Paper-II, Q14 | May/June-19, Q5(a) [MGU])
Data Structures
OR
A single linked list structure containing two
Write algorithm for operations on stack
pointers where one pointer called STACK_HEAD which
using Linked List. points to header and other called TOP which points to
(Refer Only Topics: Implementing PUSH stack Top.
Operation Using Linked List, Implementation Output
of POP Using Linked List, Implementation of A single linked list containing newly inserted
STATUS Using Linked List) ITEM.

Publishers and Distributors Pvt. Ltd. 28


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Step-1 Data Structure
Perform insertion using following operation. A single linked list containing two pointers where
new = GETNODE(Node) one pointer called STACK_HEAD points to header and
Step-2 other pointer called TOP points to Stack Top.
new ® DATA = ITEM Output
Step-3 The deleted element is placed on ITEM.
new ® LINK = TOP. Step-1
Step-4 Check whether the stack is full or empty
Assign new to TOP If TOP = NULL
TOP = new. Print “No elements on the stack”.
Step-5
Step-2
STACK_HEAD ® link = Top
Exit
Step-6
Step-3
STOP
(ii) POP Operation Go to else
This operation helps in deleting (removing) Step-4
an item from a stack. The Pop operation can also be P = TOP ® LINK 1
implemented in two ways. They are as follows, Step-5
1. By using array STACK_HEAD ® LINK 1 = P
2. By using linked list. Step-6
1. Implementation of POP Operation Using Assign P to TOP
Array TOP = P
The algorithm for implementing POP operation
Step-7
using array is as follows,
END IF
Algorithm POP_USING_ARRAY
Input Step-8
A stack containing ITEMS. Stop
Data Structure (iii) STATUS Operation
An array M with pointer called TOP. This operation helps in determining the current state
Output of a stack. The STATUS operation can be implemented
Perform deletion if stack contains ITEMS. in two ways. They are as follows,
Step-1 1. By using array
Check whether Top is full or empty 2. By using linked list.
If Top < 1 then 1. Implementation of STATUS Operation Using
Print “Deletion cannot be performed as stack is Array
empty”. The algorithm for implementing status
Step-2 operation using array is as follows,
GO TO ELSE Algorithm status_USING_Array
Step-3 Input
Assign [TOP] to ITEM A stack containing ITEM.
ITEM = M[TOP] Data Structure
Step-4 An array M containing a pointers called TOP.
Decrement Top by 1
Output
TOP = TOP – 1.
Displays information such as the amount of
Step-5
available free space and item on Top of the stack. It also
End If checks whether stack is full or empty.
Step-6
Step-1
Stop
Check whether stack is full or empty using the
2. Implementation of POP Using Linked List
following clause
The algorithm for implement POP operation using
If TOP < 1 then.
linked list is as follows,
Algorithm POP_USING_LINKED LIST Print “Stack is empty”
Input Step-2
A stack containing ITEMS. Go to else.

29 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Step-3 Step-7
If(Top > size_of_stack) then END WHILE
Printf “No elements can be inserted as stack is Full” Step-8
Step-4 If P = NULL then Print “Front =”, Top ® DATA
Else 1, Stack contains elements”, nodeCount
Step-5 Step-9
Print “ The element present on top of status is”, EndIf
A1[TOP] Step-10
Step-6 Stop
If (size_of_stack–TOP)/size_of_stack*100 1.3.2 Abstract Data Type, Representation
Step-7 Stacks using Arrays
Printf “The total free space available on stack is”, F Q48. Define in brief about Abstract Data type
Step-8 (ADT).
END IF Answer :
Step-9 Abstract Data Type (ADT)
END IF Abstract Data Type (ADT) is a data type that
Step-10 allows the programmer to use it without concentrating
Stop on the details of its implementation.
2. Implementation of STATUS Using Linked List A class can be treated as an abstract data type by
The algorithm for implementing status separating its specifications from the implementation of
operation is as follows, its operations.
Algorithm status_USING_Linked List This separation between the specifications and
Input the implementation can be obtained by,
A stack containing ITEM(elements). (i) Considering and placing all the member variables
in the private section of the class.
Data Structure
A single linked list containing two pointers where (ii) Placing all the needed operations in the public
one pointer called STACK_HEAD points to header and section and describing the ways of using these
other pointer called TOP points to stack TOP. member functions.
Output (iii) Considering all the helping functions as private
member functions and placing them in private
Displays information like stack is full or empty,
section of the class.
total number of items on the stack and the TOP most
element on stack. Class class-name
Step-1 Private
P = STACK_HEAD ® LINK 1 1. Member Variables
Step-2 2. Helping Function
Checks whether pointer(p) points to NULL or not Public
If(p = Null) then Operations needed by
Print “There are no elements on stack”. the programmer
Step-3 Table: Class as an ADT
Go to else The interface of an ADT specifies how to use it in
Step-4 our program and consists of the public member functions
Assign zero to node count along with the accompanying comments that describes
i.e., nodeCount = 0 the way to use these public member-functions.
Step-5 The implementation of an ADT specifies the
way to realize an interface as a C++ code and consists
Check whether the value of pointer ‘p’ is NULL
of private members of a class and the definitions of both
or not
the private and public member functions.
While(p ≠ NULL)
To use an ADT in our program, the only thing we
nodeCount = nodeCount + 1 need to know is its interface, but not its implementation
Step-6 i.e., implementation is not required to write the main
P = P ® LINK 1 program.

Publishers and Distributors Pvt. Ltd. 30


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Q49. What is a stack? Give the ADT for a stack. stack * create (void);
Answer : (Model Paper-III, Q14(a) | Nov./Dec.-17, Q9(b(i) [OU] stack * destroy (stack * s);
Stack bool push (stack * s, void * data);
For answer refer Unit-I, Page No. 27, Q.No. 46, void * pop(stack * s);
Topic: Stack. void * top(stack * s);
Stack ADT int count(stack * s);
In stack ADT, the structures for the data nodes bool empty (stack * s);
and head nodes and operations on stack are encapsulated. bool full (stack * s);
Thus, the stack data structure is viewed as a pointer to //end of stack ADT.
the stack structure in the ADT by the calling function. After developing a stack ADT, the programmer
Node Structure can create stack by defining a pointer to a stack and then
It consists of two pointers, a data pointer and a calling the create function. The create function returns
link node pointer. Generally, a node stores the actual the address of the stack structure. This is as shown below:
data. But in a stack ADT, the address of the actual data is stack * s;
stored in a node. Both the linked list and the stack ADT s = create( );
have similar node structure except that former stores Q50. Explain about array implementation of
the actual data, and later stores the address of the actual stack ADT.
data (i.e., pointer to data). Since, the actual type of data
Answer :
pointer is not known, it is stored as void.
Array Implementation of Stack
Head Structure
The implementation of stack using an array is
It contains two elements, one is the pointer to the done as follows,
top element and other is a count variable that keeps track
(i) The base is located at the first stack element i.e.,
of the number of elements in the stack.
at index 0.
Operations on a Stack
(ii) The insertion and deletion of data moves the top
The various operations performed on a stack are value up and down in the array.
as follows, (iii) Increment the top by 1 and use it as the array index
create( ) : Returns the address of a stack node. for the next data in order to push an element onto
destroy( ) : Returns null pointer by deleting all the stack.
the nodes in a stack. (iv) Copy the data at the index top and decrement top
push( ) : Inserts an element at the top end of by 1 in order to pop an element from the stack.
the stack. (v) A metadata element that contains the maximum
pop( ) : Deletes an element stored at the number of elements present in the stack is also
top end of the stack. required for an array implementation of stack.
count( ) : Returns the total number of The data structure for an array implementation
elements in a stack. of stack differs from the data structure for a linked list
empty( ) : Checks whether the stack is empty implementation of stack. It has three differences as
or not. If it is empty, it returns follows,
‘true’. Otherwise, it returns ‘false’. (i) The top of stack is an index, instead of a pointer.
full( ) : Checks whether the stack is full or (ii) The maximum size of a stack is known.
not. (iii) There is no requirement for next fields. Since the
The stack ADT structure is given below. stack is a LIFO structure, the stack elements are
typedef struct node adjacent to its predecessors. The efficiency of the
{ stack lies in the calculation of the size prior to the
program development.
void * dataptr;
The ADT declaration for the stack array
struct node * link; implementation is as shown below,
} NODE; typedef struct
typedef struct {
{ void** stackAry;
NODE * top; int top;
int count; int Maxsize;
} STACKADT; int count;
//Operations on stack } STACKADT;

31 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
//Prototype declaration //free the data memory and stack array
STACKADT* create(int maxsize); for(int i = 0; i < stack –> count; i + +)
STACKADT* delete(STACKADT* queue); free(stack –> stackAry[i]);
bool push(STACKADT* stack, void* elemptr); free(stack –> stackAry);
void* pop(STACKADT* stack); //free memory for stack head
bool isfull(STACKADT* stack); free(stack);
bool isempty(STACKADT* stack); }
void* stack Top(STACKADT* stack); return NULL; //Delete stack
int Count(STACKADT* stack); }
Create Stack This function returns a null pointer if the stack
In the ADT implementation of creating a stack, pointer is found to be null. If it is not null, then it free the
an empty stack is created by allocating the head structure array memory and head structure one after the other and
and the array from the dynamic memory. The ADT then returns a null pointer.
implementation is as shown below, Push Stack
STACK ADT* create (int size) The array implementation of push stack involves a
{ test for overflow. The total number of stack elements are
STACKADT* stack; compared with the maximum stack size. If the stack is
stack = (STACKADT*) malloc full then element can’t be pushed hence false is returned.
(sizeof(STACKADT*); If there is space, the data is copied to the stack, the top
index and the stack count are incremented and true is
if(! stack)
returned. The array implementation of push stack is as
{
shown below.
return NULL;
bool push(STACKADT* stack, void* data ptr)
//Head allocation
{
stack –> count = 0;
if(stack → count = = stack –> Maxsize)
stack –>top = – 1;
return false;
//stack initialization and allocation
(stack –> count) + +;
stack –> Maxsize = size;
(stack –> top) + +;
stack –> stackAry = (void**) calloc
stack –> stackAry[stack –> top] = data ptr;
(Stack –> Maxsize, sizeof(void*));
return true;
if(!stack –> stackAry)
}
Free(stack);
Pop Stack
return NULL;
The array implementation of pop stack is simple
}
and similar to the linked list implementation.
return stack;
void* pop(STACKADT* stack)
}
{
The malloc( ) function allocates memory to the
void* dataptr;
stack head structure and calloc( ) function allocates the
array of void pointers and saves the address in the stack if(stack –> count = = 0)
head structure. Both of these functions return a null dataptr = NULL;
pointer on failure. Since, the stack array in the head else
structure is a pointer to an array of void pointers, while {
casting pointer, it must be casted as to a pointer to void. dataptr = stack –> stackAry [ –> top];
The stack that is created is empty. So, the top (stack –> count) – –;
index is set to – 1. The value for a null stack must be (stack –> top) – –;
set to – 1 because a stack that holds only one element }
in it will have 0 as its top value.
return data ptr;
Delete Stack
}
The ADT implementation for delete stack is shown
When the only element in the stack is deleted,
below,
the stack will be set to null. A null stack can be defined
STACKADT* delete(STACKADT* stack) as stack with a top index of – 1. The top value will be
{ ‘0’ if only one element is left on the stack. Subtraction
if(stack) of ‘1’ from ‘0’ yields ‘– 1’ which is the flag designated
{ for the null stack.

Publishers and Distributors Pvt. Ltd. 32


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Full Stack {
A stack is full when the count and maximum case 1: if(top= =max–1)
number allocated for the array are equal. Otherwise, there
cout<<“overflow\n”;
will be a room for more data. The array implementation
of full stack is as shown below, else
bool isfull(STACKADT* stack) {
{ cout<<“enter the element:”;
return(stack –> top = = stack –> stackmax); cin>>x;
} arr[++top]=x;
Empty Stack
}
For the determination of an empty stack, the
stack count in the head structure is tested. A value true break;
is returned if the count is 0 else false is returned. The case 2: if(top<0)
array implementation of empty stack is shown below, cout<<“underflow”;
bool isempty(STACKADT* stack) else
{
cout<<“the deleted item is”<<arr[top]--;
return(stack –> count = = 0);
} break;
Stack Top case 3: if(top<0)
To retrieve the data from the top of the stack, cout<<“the stack is empty\n”;
the data in the stack is tested. If the stack is not empty, else
then the data pointer in the top element is returned. If
{
it is empty, then a null pointer is returned. The array
implementation of stack top is shown below. cout<<“the elements of the stack are:”;
void* stacktop(STACKADT* stack) for(i=0; i<=top; i++)
{ cout<<arr[i];
if(stack –> count = = 0) }
return NULL; break;
else
case 4: exit(0);
return stack –> stackAry[stack –> top];
} break;
Stack Count default: cout<<“invalid choice\n”;
The stack count that present in the stack head break;
structure is returned. Its implementation is given below. }
int count(STACKADT* stack) }
{
while(ch!=4);
return stack –> count;
} }
Q51. Write a C++ program to implement stack Output
using an array.
Answer : Nov./Dec.-19, Q9(b) [OU]
Program
#include<iostream.h>
#include<conio.h>
void main( )
{
int arr[15]={0}, i,top=–1, max=10,ch,x;
cout<<“MENU”<<endl<<“1.push”<<endl
<<“2.pop”<<endl<<“3.display”<<endl<<“4.exit”;
do
{
cout<<“\n Enter the choice:”;
cin>>ch;
switch(ch)

33 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Q52. Write a program to implement the stack return false;
abstract data type using an array. }
Answer : Nov./Dec.-19, Q9(b) [OU] }
Program void pop() //Popping an element from the stack
#include<iostream> {
#include<conio.h> if(isEmpty())
using namespace std; {
class Stack cout <<“Stack is Empty”;
{ return;
int s[10]; }
int top_ele; cout <<“The popped element is:” <<“ ”<<s[top_ele– –];
public: }
Stack() void display() // Printing the elementes in the stack
{ {
top_ele=–1; if(top_ele==–1)
} {
void push(int x) // Pushing element into the cout <<“Stack is Empty!!”;
//stack return;
{ }
if(isFull()) for(int i=top_ele;i>=0;i– –)
{ {
cout <<“Stack is full”; cout <<s[i] <<“ ”;
return; }
} }
top_ele++; };
s[top_ele]=x; int main( ) //Main function
cout <<“The pushed element is:”<<“ ”<<x; {
} int ch;
bool isFull() //Checking whether the stack is full or not Stack st;
{ while(1)
int size=sizeof(s)/sizeof(*s); {
if(top_ele == size – 1) cout <<“\n1.Push 2.Pop 3.Display 4.Exit\n”;
{ cout<<“Enter ur choice:”;
return true; cin >> ch;
} switch(ch)
else {
{ case 1: cout <<“Enter the element you want to push:”;
return false; cin >> ch;
} st.push(ch);
} break;
bool isEmpty() //Checking whether the case 2: st.pop();
//stack is empty or not break;
{ case 3: st.display();
if(top_ele ==–1) break;
{ case 4: exit(0);
return true; }
} }
else return 0;
{ }

Publishers and Distributors Pvt. Ltd. 34


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Output 1.3.4 Applications of Stacks –
Converting Infix Expression to Postfix
Expression, Evaluating the Postfix
Expression, Checking Well-formed
(Nested) Parenthesis, Processing of
Function Calls, Reversing a String
Q54. Write an algorithm to convert a given infix
expression to postfix expression.
Answer :
Algorithm to Convert Infix Expression into Postfix
Expression
Step1: Initialize stack as empty
stack = NULL
Step2: Check the expression from left to right
If an operand is encountered, add it to the ‘P’
where ‘P’ is the output postfix expression
Step3: If a left parenthesis ‘(’ is encountered push it
onto the stack.
1.3.3 Prefix, Infix, Postfix Notations for else
Arithmetic Expression If stack = NULL or if the operator has higher
precedence than the operator present on top of stack
Q53. Describe about infix, postfix, prefix
then, push the operator with higher precedence
notations.
else
Answer : Nov./Dec.-17, Q5(b)(i) [MGU]
Remove the operator from the stack and add to
Infix Expression the output postfix expression.
If an operator is placed between two operands, Step4: If a closing parenthesis ‘)’ is encountered.
then such an expression is referred to as infix expres- Then, remove the operators from the stack and
sion. Most of the arithmetic expressions are expressed add the operator to the output expression until
using this notation. left parenthesis is found. Remove the ‘(’ from
Examples stack and delete it.
A+B Step5: If the expression is analyzed completely, continue
A*B+C till stack ≠ NULL. Delete the stack and add the
(A + B) + C remaining elements to output postfix expression.
(A * C) + (B * D) Q55. Explain how to convert the given infix
Prefix Expression expression to postfix expression A*B + (C/D).
If an operator is placed before two operands, Answer :
then such an expression is referred to as prefix expres- The given expression is A * B + (C/D)
sion. It is also called polish notation.
Input Token Stack Output (Postfix)
Examples
A (Empty) A
+AB
* * A
*A + BC
++ABC B * AB
*AC + *BD + + AB*
Postfix Expression ( +( AB*
If an operator is placed after the operands, then C +( AB*C
such an expression is referred to as postfix expression. / +(/ AB*C
It is also called as reverse polish notation. D +(/ AB*CD/
Examples
) + AB*CD/
AB +
Empty (Empty) AB*CD/+
ABC +*
AB + Z + The obtained postfix expression is,
AC* BD*+ AB * CD / +

35 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Q56. Covert following expression into (X + Y*Z) – ((N*M + O)/P) into post form.
Answer : May-18, Q5(b)(ii) [MGU]

Input Token Stack Output


(X + Y * Z) – ((N * M + O)/P) Empty –
X + Y * Z) – ((N * M + O)/P) ( – If I Don’t Come,
My Method Will Come
+ Y * Z) – ((N * M + O)/P) ( X
Y * Z) – ((N * M + O)/P) (+ X
*Z) – ((N * M + O)/P) (+ XY
Z) – ((N * M + O)/P) (+* XY
) – ((N * M + O)/P) (+* XYZ
– ((N * M + O)/P) Empty XYZ * +
((N * M + O)/P) – XYZ * +
(N * M + O)/P) –( XYZ * +
N * M + O)/P) –(( XYZ * +
* M + O)/P) –(( XYZ * + N
M + O)/P) –((* XYZ * + N
+ O)/P) –((* XYZ * + NM
O)/P) –((+ XYZ * + NM *
)/P) –((+ XYZ * + NM * O
/P) –( XYZ * + NM * O +
P) –(/ XYZ * + NM * O +
) –(/ XYZ * + NM * O + P
End – XYZ * + NM * O + P /
End Empty XYZ * + NM * O + P / –
\ The post form of the given expression is “XYZ * + NM * O + P/–”.
Q57. Convert infix expression (a + b) * c/d + (e + f) to postfix expression.
Answer : Nov./Dec.-17, Q5(b)(ii) [MGU]

Input Token Stack Output


( ((
a (( a
+ ((+ a
b ((+ ab
) ( ab+
* (* ab+
c (* ab+c
/ (/ ab+c*
d (/ ab+c*d
+ (+ ab+c*d/
( (+( ab+c*d/
e (+( ab+c*d/e
+ (+(+ ab+c*d/e
f (+(+ ab+c*d/ef
) (+ ab+c*d/ef+
) ab+c*d/ef++

Publishers and Distributors Pvt. Ltd. 36


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Q58. Write a program in C++ to convert infix else
expression to postfix expression. {
(Model Paper-I, Q14 | May/June-19, Q5(b) char item1 = stack[top] ;
Answer : [MGU] | Nov./Dec.-18, Q5(b) [MGU]) top– – ;
Program return item1 ;
#include<iostream.h> }
#include<string.h> }
#include<ctype.h> void infixexp :: convert( )
#include<conio.h> {
I am complex but Worthy
const int MAX = 50 ; while ( *s1 )
class infixexp {
{ if ( *s1 == ‘ ’ || *s1 == ‘\t’ )
private : {
char target[MAX], stack[MAX] ; s1++ ;
char *s1, *t1 ; continue ;
int top ; }
public : if ( isdigit ( *s1 ) || isalpha ( *s1 ) )
infixexp( ) ; {
void setexp ( char *str ) ; while ( isdigit ( *s1 ) || isalpha ( *s1 ) )
void push ( char c1 ) ; {
char pop( ) ; *t1 = *s1 ;
void convert( ) ; s1++ ;
t1++ ;
int priority ( char c1 ) ;
}
void display( ) ;
}
};
if ( *s1 == ‘(’)
infixexp :: infixexp( )
{
{
push ( *s1 ) ;
top = –1 ;
s1++ ;
strcpy ( target, “ ” ) ;
}
strcpy ( stack, “ ” ) ;
char opr ;
t1 = target ;
if ( *s1 == ‘*’ || *s1 == ‘+’ || *s1 == ‘/’ || *s1 == ‘%’ ||
s1 = “ ” ; *s1 == ‘-’ || *s1 == ‘$’ )
} {
void infixexp :: setexp ( char *str ) if ( top != –1 )
{ {
s1 = str ; opr = pop( ) ;
} while ( priority ( opr ) >= priority ( *s1 ) )
void infixexp :: push ( char c1 ) {
{ *t1 = opr ;
if ( top == MAX ) t1++ ;
cout << “\nStack is full\n” ; opr = pop( );
else }
{ push ( opr );
top++ ; push ( *s1 );
stack[top] = c1 ; }
} else
} push ( *s1 );
char infixexp :: pop( ) s1++ ;
{ }
if ( top == –1 ) if ( *s1 == ‘)’ )
{ {
cout << “\nStack is empty\n” ; opr = pop( ) ;
return –1 ; while ( ( opr ) != ‘(’)
} {

37 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
*t1 = opr ; Q59. Explain how postfix evaluation is done.
t1++ ;
Answer :
opr = pop( ) ;
Evaluation of Postfix Expression using Stack
}
s1++ ; The steps involved in evaluating a postfix
} expression are as follows,
} 1. Initially, scan the given input from left to right,
while ( top != –1 ) move the operands on to the stack until any
{ operator is found.
char opr = pop( ) ; 2. After finding an operator remove operands
*t1 = opr ; from stack, perform operation and store current
t1++ ; result on the stack.
} 3. Repeat the above steps until the end of an
*t1 = ‘\0’ ; expression is reached.
} Example
int infixexp :: priority ( char c1)
Consider the following example to illustrate
{ the evaluation of postfix, i.e., 8 2/3 + 4 8 * +
if ( c1 == ‘$’ )
return 3 ; Stack
Token Top Action
if ( c1 == ‘*’ || c1 == ‘/’ || c1 == ‘%’ ) [0] [1] [2]
return 2 ; 8 8 [0] 8 is pushed onto stack
else 2 8 2 [1] 2 is pushed onto stack
{
[0] Evaluate 8/2 and
if ( c1 == ‘+’ || c1 == ‘–’ )
/ 4 push the result onto
return 1 ; the stack.
else
3 4 3 [1] 3 is pushed onto stack
return 0 ;
} [0] Evaluate 4 + 3 and
} + 7 push the result onto
void infixexp :: display( ) the stack
{ [1] 4 is pushed onto the
4 7 4
cout << target ; stack
} [2] 8 is pushed onto the
8 7 4 8
void main( ) stack
{ [1] Evaluate 4 * 8, place
* 7 32
char expr[MAX] ; result on the stack.
infixexp i ; [0] Evaluate 32 + 7, place
clrscr(); + 39
result on the stack.
cout << “\n Enter an expression in infix form: ”
; Q60. Evaluate the postfix 1 2 3 * + 4 –
cin.getline ( expr, MAX ) ; expression.
i.setexp ( expr ) ; Answer :
i.convert( ) ;
Given postfix expression is, 1 2 3 * + 4 –
cout << “\n The postfix expression is: ” ;
i.display(); Step-1
getch(); Initially push the operand ‘1’ on to the stack.
}
Output

1
push 1

Publishers and Distributors Pvt. Ltd. 38


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Step-2 Step-7
Now, push the operand ‘2’ on to the stack. Push the operator ‘–’ on to the stack and
perform 7 – 4 and store the result on the stack.
The result value is ‘3’.

2 –

4
1
7 3
push 2
push –
7 – 4 is performed
Step-3
\ The evaluation of postfix expression ‘1 2 3 * + 4 –’ is 3.
Push the operand ‘3’ on to the stack.
Q61. Evaluate the postfix operation which is
formed for the infix expression (A + B * C
3
/ D + E), for A = 5, B = 4, C = 3, D = 6, E = 2.

2
Answer :
Given infix expression is,
1
A+B*C/D+E
push 3
Evaluation of the Postfix Expression for the Given
Step-4 Values
Push the operator * onto the stack. Now, The postfix expression is ABC * D/+E+
evaluate 2 * 3 and store the result onto the Here, A = 5, B = 4, C = 3, D = 6, E = 2. (So,
stack. expression will be 543 *6/+2+)

*
1. Initially, push the operand ‘A’ onto the stack.
3

2 6

1 1
push * 2 * 3 is performed

Step-5 5
Push the operator ‘+’ and perform 1 + 6 then push 5
store the result on to the stack.
2. Now, push the operand ‘B’ onto the stack.

+

6

1 7 4
push + 1 + 6 is performed
5
Step-6 push 4
Push the operand ‘4’ onto the stack.
3. Push the operand ‘C’ onto the stack.

3
4 4

7 5

push 4 push 3

39 Publishers and Distributors Pvt. Ltd.
Computer Science Paper-III Data Structures Using C++
4. Push the operator ‘+’ onto the stack. So, 9. Finally, push the operator ‘+’ on to the stack.
evaluate 4*3 and store the result onto the stack. So, evaluate 7 + 2 and store the result on to the
stack. The resultant value is ‘9’
*
3
⇒ +
4 12 ⇒
2
5 5
push '*' 7 9
4 * 3 is performed
push + 7 + 2 is performed
5. Push the operand ‘D’ onto the stack.
∴ The evaluation of postfix operation (A
C*D/+E+) for the given values is ‘9’.
6 Q62. Write C++ program for postfix evaluation
using stack.
12 Answer :
5 Program
push 6 // A simple C++ program for postfix evaluation
//using stack
6. Now, push the operator ‘/’ on to the stack. So, #include<stdio.h> //Header file section
evaluate 12/6 and store the result on to the
#include<conio.h>
stack.
#include<stdlib.h>
/ #include<math.h>
6 #include<ctype.h>
⇒ #include<iostream>
12 2
#define MAX 100
5 5 using namespace std;
push / 12/6 is performed struct postfx //Global declaration
7. Push the operator ‘+’ on to the stack. So, {
evaluate 5 + 2 and store the result on to the int stack[MAX];
stack. int top, n;
char *c;
};
+ void postfx(struct postfx*);
⇒ void setexpr(struct postfx*,char*);
2
void push(struct postfx*,int);
5 7 int pop(struct postfx*);
void calculate(struct postfx*);
push + 5 + 2 is performed
void display(struct postfx);
8. Push the operand ‘E’ onto the stack. int main( ) //Main program section
{
struct postfx b;
char expr[MAX];
postfx(&b); //This function is used to store
2
//the variable
7 cout<<“\nEnter postfix expression to be evaluated:”;
gets(expr); //This function reads the
push 2 //expression from the user

Publishers and Distributors Pvt. Ltd. 40


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
setexpr(&b, expr); if(isdigit(*(a ->c)))
//This function sets the expression {
//in desired variable a -> n = *(a -> c) - ‘0’;
calculate(&b); push(a, a ->n);
display(b); }
return 0;
else
}
{
void postfx(struct postfx *a)
n1 = pop(a);
// This function is used to store the expression
n2 = pop(a);
{
a -> top = – 1; switch(*(a -> c))
} {
void setexpr(struct postfx *a, char *str) case ‘+’:
// This function is used to set the expression n3 = n2 + n1;
{ break;
a -> c = str; case ‘-’:
} n3 = n2 – n1;
void push(struct postfx *a, int item) break;
// This function is used to add values into stack case ‘/’:
{ n3 = n2 / n1;
if(a -> top == MAX – 1) break;
printf(“\nStack is full”); case ‘*’:
else
n3 = n2 * n1;
{
break;
a -> top++;
case ‘%’:
a -> stack[a -> top] = item;
} n3 = n2 % n1;
} break;
int pop(struct postfx *a) case ‘$’:
// This function is used to remove values from stack n3 = pow (n2, n1);
{ break;
int data; default:
if (a -> top == – 1) cout<<“Unknown operator”;
{ exit(1);
cout<< “\nStack is empty”; }
return 0; push(a, n3);
} }
data = a -> stack[a -> top]; a -> c++;
a -> top –;
}
return data;
}
}
void display(struct postfx a)
void calculate(struct postfx *a)
// This function is used to display the expression
// This function is used to calculate the value
{ {
int n1, n2, n3; a.n = pop (&a);
while(*(a -> c)) cout<<“The Resultant value is:”<< a.n;
{ }
if((*(a->c)== ‘ ’)||(*(a->c)== ‘lt’)) Output
{
a -> c ++;
continue;
}

41 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Q63. Write how correctness of well-formed parentheses is checked.
Answer :
Checking the Correctness of Well-formed Parentheses
The various conditions to check the correctness of well-formed parentheses are as follows,
1. An expression should contain same number of left and right parenthesis.
2. Every left parentheses of an expression should be succeeded by the respective right parentheses.
Some expressions do not follow the above conditions. For example, the expression ((P + Q)(R + S)) violates
the condition 1 since it does not contain equal number of left and right parenthesis.
Inorder to solve the above problems the concept of parentheses count is introduced. Parentheses count at a
specific point in an expression is the difference between the left parenthesis count and the right parentheses count.
To confirm that the expression is with the well-formed parenthesis it must follow the below mentioned rules.
1. Parentheses count should be non-negative at any point in an expression.
2. The parentheses count should be zero at the end of the expression.
Example: Consider an expression, E = ((A × B) + (C/(D * E))).
The parentheses count at the end of the expression is 0 i.e., (4 – 4 = 0).
The parentheses count at point C is 2 (i.e., 3 – 1) which is non-negative number.
The expression follows, both the rules and is said to be with well-formed parentheses.
Stack can be used to check the correctness of a well-formed parentheses when a left parenthesis is countered
it is pushed onto the stack and when right parenthesis is encountered then the stack is examined. Stack must be
empty when end of the string is reached, otherwise the expression/string is said to be invalid.
Q64. Explain how function calls are processed.
Answer :
Processing of Function Calls
Stack is one of the frequently used concept for processing of function calls and termination. This process
works based on the LIFO (Last in First Out) property. The function need to return the value to the place where it
is called. This should be remembered by the program. The function that is called first will be completed last and
the function that is called last will be completed first. Let P and Q be two functions in addition to main function.
Assume that the main function calls P and P calls Q. The function P cannot terminate until the function Q has
completed and returned a value. Similarly, the main function will be terminated only after the execution of function
P has completed and returns a value. Therefore, the main function that is called first will be completed at last. The
processing of function calls can be depicted as,
Q()
{
P() cout<<“Q( )”;
main ( ) { cout<<“Begin”;
{ cout<<“P( )”; ---
cout<<“main ( )” cout<<“Begin”;
cout<<“Begin”; ---
Q( ); cout<<“end”;
P( ); qa --
pa ---
cout<<“end”; }
cout<<“end”; --
-- }
}

Here, stack is used to store return addresses i.e pa and qa. The processing of function calls by using
stack is as follows.
Stack implementation
main starts ← First in main( )
P starts
P( )
main( )

Q starts ← last in Q( )
..... P( )
..... main( )

Q ends ← First out P( )


main( )

main( )
P ends

main ends ← last out Empty stack

Publishers and Distributors Pvt. Ltd. 42


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III
Q65. Explain in detail the process of reversing a string. Model Paper-III, Q14(b)
OR Don’t Think
I am Complex
Reverse the string “ABCDEF” using stack.
(Refer Only Topic: Example)
Answer : Nov./Dec.-17, Q9(b)(ii) [OU]
Reversing a String using a Stack
The stack concept is the best and efficient way to reverse a string that is in sequential
order. The LIFO (Last in First Out) property of stack ensures string reversal. Each of single character is pushed into
the stack sequentially until the end of string is reached. Then stack pops the top element repeatedly and displays
each element, until the stacks empty. With this the elements will be displayed in reverse order.
Example
Reversing the string ABCDEF using stack is given below,
Input Action Stack Display
ABCDEF Push A A ← top of the stack –
BCDEF Push B AB ← top of the stack –
CDEF Push C ABC ← top of the stack –
DEF Push D ABCD ← top of the stack –
EF Push E ABCDE ← top of the stack –
F Push F ABCDEF ← top of the stack –
End Pop ‘F’ and display ABCDE ← top of the stack F
Pop ‘E’ and display ABCD ← top of the stack FE
Pop ‘D’ and display ABC ← top of the stack FED
Pop ‘C’ and display AB ← top of the stack FEDC
Pop ‘B’ and display A ← top of the stack FEDCB
Pop ‘A’ and display Stack is empty FEDCBA
Program
#include<iostream.h>
#include<string.h>
#define MAX 20
int ele;
int top = –1;
char stack_array[MAX];
void push(char ele);
int isEmpty( );
int isFull( );
char pop( );
void main( )
{
char stack_string[30];
int count;
cout<<Enter A String:;
cin>>stack_string;
for(count = 0; count < strlen(stack_string); count++)
{
push(stack_string[count]);
}
for(count = 0; count < strlen(stack_string); count++)
{
stack_string[count] = pop( );
}

43 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
cout<<stack_string; Output
}
void push(char ele)
{
if(isFull( ))
{ Q66. Explain how a stack is used in the follow-
cout<<“Stack Overflow”; ing applications.

} (i) Processing of function


calls
else Hey!
(ii) Reversing a string Don’t
{ escape
(iii) Checking correctness from
top = top + 1; me
of well-formed paren-
stack_array[top] = ele; theses.
} Answer : June/July-19, Q9(b) [OU]
}
(i) Processing of Function Calls
char pop( )
For answer refer Unit-I, Page No. 42, Q.No. 64.
{
(ii) Reversing a String
if(isEmpty( ))
For answer refer Unit-I, Page No. 43, Q.No. 65.
{
cout<<“Stack Underflow”; (iii) Checking Correctness of Well-formed
Parentheses
return 1;
For answer refer Unit-I, Page No. 42, Q.No. 63.
}
else
{
ele = stack_array[top];
top = top – 1;
return ele;
}
}
int isEmpty( )
{
if(top == –1)
return 1;
else
return 0;
}
int isFull( )
{
if(top == MAX–1)
return 1;
else
return 0;
}

Publishers and Distributors Pvt. Ltd. 44


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III

EXERCIsE AND PRACTICE QUEsTIoNs

Short Questions

1. Define data structure and describe the types of data structure. (Refer Q1) Nov./Dec.-19, Q1 [OU]

2. Define a Data structure in terms of the triplet (D, F, A).


Give an example. (Refer Q2) June/July-19, Q1 [OU]

3. What is the difference between Atomic and Composite data


with examples? (Refer Q3) Nov./Dec.-18, Q1 [OU]

4. Define an algorithm. Write the essential characteristics of


an algorithm. (Refer Q4) May/June-18, Q1 [OU]

5. What is Flowchart? (Refer Q5) May/June-19, Q1 [MGU]

6. What are pros and cons of Arrays? (Refer Q9) Nov./Dec.-18, Q1 [MGU]

OR
Write the advantages and disadvantages of arrays. (Refer Q9) Nov./Dec.-17, Q1 [OU]

7. What is Sequential Organization? Briefly explain its advantages


and disadvantages. (Refer Q10) Nov./Dec.-18, Q2 [OU]

8. Define stack. List the operations of stack. (Refer Q11) Nov./Dec.-19, Q2 [MGU]

9. What is stack? List out applications of stack. (Refer Q14) Nov./Dec.-19, Q2 [OU]

OR
List the applications of stacks. (Refer Q14) May-18, Q1 [MGU]

OR
What are the applications of stacks? (Refer Q14) June/July-19, Q3 [OU]

10. Define infix expression. (Refer Q16) Nov./Dec.-19, Q1 [MGU]

11. What are the advantages of prefix and postfix expression? (Refer Q17) June/July-19, Q2 [OU]

12. Explain the postfix expression evaluation with an example. (Refer Q18) Nov./Dec.-17, Q2 [OU]

13. Transform the following infix expressions into their equivalent


postfix expressions,
A + B × (C + D) / F + D × E and (A + B ^ D) / (E – F) + G (Refer Q19) May/June-18, Q2 [OU]

14. Explain about reversing a string. (Refer Q20) Nov./Dec.-17, Q1 [MGU]

Essay Questions

15. Briefly describe about the various types of data structure. (Refer Q22) Nov./Dec.-17,Q9(a)(i) [OU]

16. Explain the concept of subalgorithms. Write an algorithm to


compute the following using a subalgorithm:
P = n! / (n – r)! (Refer Q26) June/July-19, Q9(a) [OU]

17. Define an algorithm. Write a flowchart and a pseudo-code to


compute the sum of the first N natural numbers. (Refer Q28) Nov./Dec.-17, Q9(a)(ii) [OU]

18. Explain in detail about how Algorithms are analyzed. (Refer Q30) Nov./Dec.-19, Q7(a) [MGU]

45 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

19. Define ADT for the “Integer” and explain all its functions and
axioms in detail. (Refer Q32) Nov./Dec.-18, Q9(a) [OU]

20. Write a C++ program to implement the following operations


an Arrays.

(i) To insert an element at a given position

(ii) To delete an element at a given position. (Refer Q34) Nov./Dec.-18, Q9(b) [OU]

21. Explain row-major and column-major memory representations


for 2-D arrays. (Refer Q36) May/June-18, Q9(a)(i) [OU]

22. Consider an integer array, int A[3][4] in C++. If the base address
is 1050, find the address of the element A[2][3] with row-major
and column-major representations of the array. (Refer Q37) May/June-18, Q9(a)(ii) [OU]

23. Write short notes on the following:

(i) Memory representation and address calculation of 1-D, 2-D arrays

(ii) Different types of data structures. (Refer Q38) Nov./Dec.-17, Q5(a) [MGU]

OR

Explain memory representation and address calculation of


1-D and 2-D arrays. (Refer Q38) Nov./Dec.-19, Q9(a)(ii) [OU]

24. What is an array? Explain about different types of arrays. (Refer Q40) May-18, Q5(a) [MGU])

25. What is an array and explain its advantages and


disadvantages? (Refer Q45) Nov./Dec.-19, Q9(a)(i) [OU]

26. Explain the stack operations with program codes and


examples. (Refer Q46) May/June-18, Q9(b) [OU]

OR

Define stack. Give a brief introduction on stack. (Refer Q46) Nov./Dec.-19, Q7(b) [MGU]

27. Explain the primitive operations on STACKS with arrays. (Refer Q47) Nov./Dec.-18, Q5(a) [MGU]

OR

Explain about operations on stack. (Refer Q47) May-18, Q5(b)(i) [MGU]

OR

Explain the primitive operations of STACK. (Refer Q47) May/June-19, Q5(a) [MGU]

OR

Write algorithm for operations on stack using Linked List. (Refer Q47) Nov./Dec.-17, Q6(b) [MGU]

28. What is a stack? Give the ADT for a stack. (Refer Q49) Nov./Dec.-17, Q9(b(i) [OU]

29. Write a C++ program to implement stack using an array. (Refer Q51) Nov./Dec.-19, Q9(b) [OU]

30. Write a program to implement the stack abstract data type


using an array. (Refer Q52) Nov./Dec.-19, Q9(b) [OU]

31. Describe about infix, postfix, prefix notations. (Refer Q53) Nov./Dec.-17, Q5(b)(i) [MGU]

Publishers and Distributors Pvt. Ltd. 46


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III

32. Covert following expression into (X + Y*Z) – ((N*M + O)/P)


into post form. (Refer Q56) May-18, Q5(b)(ii) [MGU]

33. Convert infix expression (a + b) * c/d + (e + f) to postfix


expression. (Refer Q57) Nov./Dec.-17, Q5(b)(ii) [MGU]

34. Write a program in C++ to convert infix expression to postfix


expression. (Refer Q58) (May/June-19, Q5(b) [MGU] | Nov./Dec.-18, Q5(b) [MGU])

35. Reverse the string “ABCDEF” using stack. (Refer Q65) Nov./Dec.-17, Q9(b)(ii) [OU]

36. Explain how a stack is used in the following applications.


(i) Processing of function calls
(ii) Reversing a string
(iii) Checking correctness of well-formed parentheses. (Refer Q66) June/July-19, Q9(b) [OU]

47 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

INTERNAL AssEssMENT/EXAM

I Multiple Choice
1. The value after evaluating the postfix expression, AB + C + – D ↑ GH + * for A = 1, B = 10, C = 1,
D = 2, G = – 1 and H = 6 is __________. [ ]
(a) 530 (b) 590
(c) 600 (d) 720
2. Big O notation is utilized mainly because, [ ]
(i) It is average bound of the growth rate of the algorithm
(ii) It can be used to decide the best algorithm which can be used to solve given problem
(iii) It determines the maximum size of a problem that can be solved in a given system in a given
amount of time
(iv) It is the lower bound of the growth rate of the algorithm.
(a) Both (i) and (ii) (b) Both (ii) and (iii)
(c) All the above (d) None of the above
3. Array is also used to represent __________. [ ]
(a) Graphs (b) Trees
(c) Strings (d) Both (a) and (b)
4. The performance of an algorithm is analyzed using __________. [ ]
(a) Time complexity (b) Space complexity
(c) Null complexity (d) Both (a) and (b)
5. Which of the following is not an application of stack? [ ]
(a) Handling recursive programming (b) Evaluation of postfix expressions
(c) Job scheduling (d) Reversing list
6. Which among the following properties does not hold good in a stack? [ ]
(a) A stack supports the principle of last in first out
(b) A linear stack has limited capacity
(c) A push operation decrements the top pointer
(d) A pop operation deletes an item from the stack
7. Postfix expression for a + b * c – d [ ]
(a) abc* + d – (b) abcd + * –
(c) ab + cd – * (d) abc * + – d
8. In ____ notation, the operator is placed between the two operands. [ ]
(a) Prefix (b) Postfix
(c) Infix (d) None of the above
9. _____ operation helps in inserting an ITEM (element) onto the stack. [ ]
(a) PUSH (b) POP
(c) STATUS (d) None of the above
10. The application of stack includes ________. [ ]
(a) Reversing data (b) Recursion(factorial calculation)
(c) Evaluation of arithmetic expression (d) All the above

Publishers and Distributors Pvt. Ltd. 48


UNIT-1: Fundamental Concepts, Linear Data Structure Using Arrays and Stacks Computer Science Paper-III

II Fill in the Blanks


1. Data structures are classified into _____ and _____.

2. A data structure in which all the data elements are stored in sequential manner is called _____

3. _____ arrays stores the data in the form of a matrix

4. The simplest form of an array is _____.

5. A _____ is a series of characters which is treated as a single data item

6. Stacks are used in the conversion of expression from infix to _____ expression

7. The elements in a stack can be inserted and deleted at only one end called _____.

8. In array representation, memory blocks of consecutive size are created for storing fixed size stack in
a _____.

9. _____ is the graphical representation of an algorithm.

10. _____ is a step-by-step process of solving a particular problem.

KEY
I. Multiple Choice
1. (c) 2. (b) 3. (d) 4. (d) 5. (c)

6. (c) 7. (a) 8. (c) 9. (a) 10. (d)

II. Fill in the Blanks


1. Linear, non linear data structure

2. Linear data structure

3. Two-dimensional

4. One-dimensional array

5. String

6. Post and prefix

7. Top

8. Sequential manner

9. Flowchart

10. Algorithm

49 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

III Very Short Questions and Answers

Q1. Define algorithm.


Answer :
An algorithm is a method of representing the step-by-step procedure for solving a problem.
Q2. What is an array?
Answer :
An array is a variable which is capable of holding fixed values in contiguous memory locations.
Q3. Define stack.
Answer :
Stack is a linear data structure. The elements in a stack can be inserted and deleted at only one end called
ton. Stack is also said to be Last-In-First Out (LIFO).
Q4. What is meant by data structure?
Answer :
Data structure can be defined as a way of organizing the data in the memory. Here data denotes a set of data
elements and set of operations performed on it.
Q5. Discuss the concept of ordered list.
Answer :
Ordered list is a list that consists of linear elements that follow some specific sequence.

Publishers and Distributors Pvt. Ltd. 50


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III

UNIT
2 Recursion, Queues and Linked
Lists

SYLLABUs
Recursion: Introduction, Recurrence, Use of Stack in Recursion, Variants of Recursion, Execution
of Recursive Calls, Recursive Functions, Iteration Versus Recursion.

Queues: Concept, Primitive Operations, Abstract Data Type, Representation Queues Using Arrays,
Circular Queue, Double-ended Queue, Applications of Queues.

Linked Lists: Introduction, Concept, Terminology, Primitive Operations – Creating, Inserting,


Deleting, Traversing, Representation of Linked Lists, Linked List Abstract Data Type, Linked List
Variants – Singly Linked List, Doubly Linked List, Linear and Circular Linked List, Representation
Stacks and Queues Using Linked Singly Lists, Application of Linked List – Garbage Collection.

LEARNING OBJECTIVEs
 Recursion and its Variants.
 Queues and its Representation using Array.
 Linked List and its Variants.
 Representation of Stacks and Queues using Singly Linked Lists.
 Application of Linked Lists.

INTRoDUCTIoN
Recursion is the process or technique by which a function calls itself. A recursive function
contains a statement within its body which calls the same function. Linked list stores
similar type of data in memory. There are three types of linked list: Singly linked list,
Doubly Linked List and Circular Linked List. Queue is an ordered collection of items in
which items can be inserted at one end called Rear end and items can be deleted from other
end called Front end.

51 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

P a r t- A S h o rt Q u e s t i o n s a n d A n s w e r s

Q1. Explain Recursion with example.


Answer : May/June-19, Q2 [MGU]

Recursion
Recursion is the process or technique by which a function calls itself. This function is called recursive
function. It contains a statement within its body, which calls the same function. Thus, it is also called as circular
definition. A recursion can be classified as direct recursion and indirect recursion. In direct recursion, the function
calls itself and in the indirect recursion, a function (f1) calls another function (f2), and the called function (f2) calls
the calling function (f1).
ant Like Wa
Example po r t ter
Im
Implementation of factorial using direct recursion is.
int fact(int n)
{
int f;
if(n == 0 ¦¦ n = = 1)
f =1;
else
f = n * fact(n – 1); /* Here fact function is calling itself*/
return f;
}
d
Q2. What are the advantages of recursion? t an Simple
Shor
Answer : Nov./Dec.-19, Q3 [MGU]
The advantages of recursion are as follows,
1. Recursive function is small, simple and more reliable than other coded versions of the program.
2. It solves the problem in the most general way as possible.
3. It is used to solve the more complex problems that have repetitive structure.
4. It is more useful because sometimes a problem is naturally recursive.
Q3. Write a recursive algorithm to find XY.
Answer : June/July-19, Q4 OU]

Recursive Algorithm to Find X Y

1. Begin
2. Declare function name as power( ) with two parameters X, Y.
3. if (Y = = 0) then return 1
4. else if (Y = = 1) then return X
5. else
6. return (X * power (X, Y – 1));
7. end if
8. Print the value of power(X, Y)
9. End.
Q4. What are the demerits or recursion?
Answer : Nov./Dec.-18, Q4 [OU]

The demerits of recursion are as follows,


1. Usage of recursion incurs overhead, since this technique is implemented using function calls.
2. Whenever a recursive call is made, some of the system’s memory is consumed.

Publishers and Distributors Pvt. Ltd. 52


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Q5. Differentiate between iteration and recur- Step 2
sion approaches in problem solving. The factorial(3) returns 3 * factorial(2) since,
Answer : Nov./Dec.-17, Q3 [OU] 3 ≠ 1. So, push 3 * factorial(2) onto the stack.
Iteration Versus Recursion
Recursion is a top down approach whereas
Iteration is a bottom-up approach. In Recursion, every
problem is divided into sub-problems among which it 3*Factorial(2)
chooses any one step and postpones the other steps. In Factorial(3)
iteration, the process starts with the known condition Stack
and then it finds the solution in step-by-step manner.
Step 3
Limitations of Recursive Algorithms
1. Recursion is not supported by most of the The factorial(2) returns 2 * factorial(1), since 2
programming language such as FORTRAN, ≠ 1. So, push 2 * factorial(1) onto the stack.
COBOL. Therefore, the recursive mathematical
function will be implemented by using iterative
methods. 2*Factorial(1)
2. Recursive mathematical functions can be 3*Factorial(2)
easily implemented but they involve additional Factorial(3)
execution time and memory.
Stack
Limitations of Iterative Methods
Step 4
1. Iterative is complex and difficult to read and
understand. The function factorial(1), returns 1.
2. The iterative methods require loop statements
along with complex logic. 1
Q6. What is the purpose of a stack in imple- 2*Factorial(1)
menting a recursive procedure? 3*Factorial(2)
Nov./Dec.-17, Q2 [MGU] Factorial(3)
OR Stack
Explain the use of Stack to find the facto- Step 5
rial of a number using recursion. Pop 2 and substitute factorial(1) = 1.
Answer : (Model Paper-III, Q6 | Nov./Dec.-18, Q3 [OU])
Recursion mostly makes use of stack for 2*1 2
implementation. It is the memory area that stores 3*Factorial(2) = 3*Factorial(2)
temporary variables and acts depending upon LIFO
principle. Consider the below recursive function. Factorial(3) Factorial(3)
int factorial (int n) Stack Stack
{ Step 6
if(n = = 1) Pop 2 and substitute factorial(2) = 2.
Remember me
return n; with concept

else 3*2 = 6
return n * factorial (n – 1); Factorial(3) Factorial(3)
} Stack Stack
If n = 3, the function call factorial (3) is made. Step 7
The execution of this call can be explained using stack Pop 6. Thus, the function call factorial(3) returns
as follows,
the value 6.
Step 1
Q7. Describe execution of recursive calls with
Push factorial(3) into the stack. example.
Answer : Nov./Dec.-19, Q4 [OU]
Each time a recursive call is made the values of
reference parameters, local variables, function value and
return address are pushed onto the stack. The data that is
Factorial(3)
pushed onto the system stack is maintained in the stack
Stack frame.
53 Publishers and Distributors Pvt. Ltd.
Computer Science Paper-III Data Structures Using C++
The following are the elements contained in a create( ) : Allocates a node for the queue
stack frame. header, and returns the reference
(i) Reference parameters that the called function of the queue head.
processes destroy( ) : Deletes all the elements of a queue
(ii) Local variables of calling function and makes each node free.
(iii) Return address front( ) : Returns reference of the element
(iv) Expression to receive the return value. stored at the front end of a queue.
The below steps are performed upon the rear( ) : Returns reference of the element
completion of all recursive calls. stored at the rear end of a queue.
(i) A normal return is executed when the stack enqueue ( ) : Checks for the availability of
contains no elements. memory to insert new node at the
(ii) When the stack contains elements, pop is rear end of queue, it returns true
performed on the stack frame to extract the top if memory is available otherwise
values of the parameters and assign them to their returns false.
variables. dequeue( ) : Returns true when deletion ends
(iii) The return address is used for finding the location successfully otherwise returns
of the call. false.
(iv) The statements are executed from the position empty( ) : Checks whether the queue is empty.
where the call is made. If it is empty returns true otherwise
returns false.
(v) Move to step (i).
full( ) : Checks whether the queue is full.
Q8. Explain briefly about queue and dequeue.
If it is full returns true otherwise
Answer : Model Paper-II, Q4 returns false.
Queue size( ) : Returns the total number of
A queue is an ordered collection of items in elements stored in a queue.
which new items may be inserted at one end known as
Q10. Define circular queue.
rear and existing items may be deleted from other end
known as front end. Answer : (Model Paper-II, Q5 | Nov./Dec.-19, Q4 [MGU])

Queue is also known as FIFO (first-in-first-out) Circular queue is introduced


structure because the element which is inserted first to overcome the drawback of nor-
will be the first element to be deleted. Diagrammati- mal queue, wherein despite of space
cally it is shown as, available at the front, insertions were
Deletion Insertion
not possible. Circular queue is simi-
Remember me
lar to ordinary queue, but the major with concept
a b c d difference is that in former the rear
Queue pointer can point to the front element. Both the pointers
Front Rear
move in clockwise direction. The major advantage of
Figure: Queue circular queue is that it is possible to perform insertion
Deque in the queue if there are empty slots at the beginning.
Insertions in queue takes place only at the rear Q11. Write a short notes on double-ended
side and deletions takes place only at the front side of the queue (DEQUE).
queue. In deque, there is no such particular restriction, Answer : Nov./Dec.-17, Q4 [OU]
insertion and deletion can take place at any side of the The deletion of an element
queue. Hence, we refer to deque as double ended queue. from a queue is known as dequeue.
Q9. Explain queue ADT. The dequeue operation first checks
Answer : Model Paper-III, Q5 for the availability of data in the
queue. If there is data in the queue,
The queue abstract data type consists of data type it deletes the data then it sends the address of the deleted
definitions and queue operations. The queue ADT type element to calling function through reference parameter
definitions define two structures, namely node structure and adjusts the pointer. Then after, it decrements the
and head structure. count variable. On successful deletion of an element, it
The node structure contains two pointers in which returns true. Otherwise, it returns false.
a pointer of type void is used to point data and another bool dequeue (QUEUEADT * queueadt, void ** datapointer)
link pointer is used to refer the next element in the queue.
The head structure contains two pointers front and rear {
that point to front and rear end of the queue respectively. NODE * deleteNode;
The operations on the queue are as follows, if(!queueadt –> count)

Publishers and Distributors Pvt. Ltd. 54


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
return 0; Q13. Define a linked list with example.
* element = queueadt –> front –> data ptr;
Answer : Model Paper-III, Q4
deleteNode = queueadt –> front;
if(queueadt –> count = = 1) Linked List
queueadt –> rear = queueadt –> front = NULL; Linked list is a linear data structure used to store
//deleting datapointer similar data in memory. The elements in linked list are
else not stored in adjacent memory locations but are stored
queueadt –> front = queueadt –> front –>link; randomly. Linked list is a collection of elements known
(queueadt –> count) – –; as nodes which contain two fields of information. One
contains the data item and the other contains the link
free (deleteNode);
or address of the successor element. A node can be
return 1; represented as,
}
Node
Q12. Write a short notes on applications of
queues. data item link data item link
Answer : (Model Paper-II, Q6 | May/June-18, Q3 [OU])
Figure: Node
The different applications of queue are as follows,
Example
1. Josephus Problem
Josephus problem is solved 21 101 – 14 203 31 NULL
by making use of circular queue. Figure: Linked List
This problem can be illustrated with
the help of the following example Q14. List the advantages and disadvantages
let us assume a group of solidiers of linked list.
are surrounded by an enemy force. Keep an eye on me Answer : Model Paper-I, Q4
Such that the victory can’t be achieved since there is
only one horse available to escape. Here, the soldiers are Advantages
grouped to form a circle and a number ‘M’ is picked to start
1. Linked list is easy to implement.
the count as well as the name of any soldier is picked using
a hat. The process starts with particular soldier by counting 2. It is a dynamic data structure.
around the circle in clock wise direction. If the count has
3. It can grow as well as shrink during run time.
reached to M then that particular soldier is removed from
the circle and the process continues by starting it from the Disadvantages
next soldier. Therefore, this process is repeated until one
1. It requires extra memory space to store pointers.
soldier is left out in the circle. The last soldier who is left
will have a chance to escape by taking the horse. 2. It can be traversed only in one direction.
2. Job Scheduling 3. Difficult to sort the elements of a linked list.
Job scheduling is the process of scheduling the
4. It requires huge amount of time accessing each
jobs in the specific order in which they are to be executed.
element.
Consider a list containing ‘m’ jobs that are needed to be
scheduled. Each job ‘j’ is assigned with a deadline. Q15. What is single linked circular list?
dlj ≥ 0 and a profit pfj ≥ 0 respectively. Each job Answer : Model Paper-I, Q5
‘j’ is said to be profitable when it is finished before its
deadline. So, a feasible solution that can be obtained is A circular linked list is a list in which the link
the total sum of all profits. field of the last node points to the first node in the list.
In circular linked list, there is no NULL link to indicate
3. Simulation
the end of the list. For this purpose, it uses a pointer
Simulation deals with modeling real time called the header that stores the address of the first
problem, in the form of a computer program, under the node. The header is used to stop iterating through the
control of various parameters. list after traversing the list once.
An advantage of simulation is that it allows to
Header
experiment the dangerous operations (like, military, etc)
virtually instead of actual field test.
Data Data Data
Any process, that is to be simulated is called a
system. System is a collection of interconnected objects,
with many inputs and produces at least a single output. Figure: Circular Linked List

55 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Q16. Discuss in brief about double linked list.
Answer :
In a double linked list, every list of element has both a reference to the next element and a reference to the
previous element. Hence, diagrammatically a node is represented as, double linked list can traverse in both directions
and it uses two pointers.

LLINK Info RLINK

Figure: Node
L R

NULL 10 20 30 NULL

Figure: Double Linked List


RLINK contains the address of succeeding node and LLink contains the address of predecessor node. The
LLink of the first node and RLINK of the last node holds NULL. The Info fields contains the actual data.

Q17. What are the advantages of circularly list over single linked list?

Answer : May-18, Q2 [MGU]

The advantages of singly circular linked list over singly linked list are as follows,
1. Any node can be easily accessed by looping through the nodes since the list is circular.
2. It is efficient compared to singly linked list in the implementation of the operations.
3. The list can be easily traversed from any node to any node.
4. It requires only one pointer to indicate the front and rear of the list rather than two pointers.

Q18. Explain the insertion of a node in singly linked lists with examples.

Answer : May/June-18, Q4 [OU]

This operation adds a new node to the linked list. This can be done in one of the three ways:
(i) Insertion of node at the beginning of the list. 2000
(ii) Insertion of node at the end of the list.
(iii) Insertion of node at a specified position in the list.
(i) Insertion of Node at the Beginning of the List
The steps to insert a node at the beginning of the list is as follows,
(a) Make link field of the new node point to the first node in the list.
(b) This new node becomes the first node.
(c) And later make the header node point to this new node.
Example
Consider an example of inserting the value 15 at the beginning of the list. Initially, the list contains
the following elements.
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL
Figure: Before Insertion

Publishers and Distributors Pvt. Ltd. 56


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
 A new node is created at the beginning of the list.
Header New Node 1000 2000 3000
5000 15 1000 3 2000 19 3000 5 NULL
 The value gets inserted at the beginning of the list.
Header New Node 1000 2000 3000
5000 15 1000 3 2000 19 3000 5 NULL
Figure: After Insertion
(ii) Insertion of the Node at the End of the List
The steps for inserting a new node at the end of the list is as follows,
(a) Traverse the list from first node to last node.
(b) Make the link field containing NULL to point to the address of the new node.
(c) This new node becomes the last node in list. And, the link field stores the NULL value.
Example
Consider an example of inserting value 15 at the end of list. Initially the list contains the following elements,
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL
Figure: Before Insertion
v A new node holding NULL is created at end of the list.
HEADER 1000 2000 3000 new node
1000 3 2000 19 3000 5 4000 Data field NULL
v The value 15 is added at the end of list.
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 4000 15 NULL
Figure: After Insertion
(iii) Insertion of Node at the Specified Location in the List
To insert a node between two nodes for instance between ith node and(i+1)th node,
(a) Link is first traversed up to the ith node.
(b) Then the link field of ith node is made to hold the address of the new node and
(c) The link field of the new node is made to hold the address of the (i+1)th node.
Example
Consider an example of inserting value 15 between 3 and 19. Initially the list contains the following elements.
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL
Figure: Before Insertion
v A new node containing address of next field is created between the 3 and 19.
1000 1500 2000 3000
1000 3 1000 3 2000 19 3000 5 NULL
↑ link field
v Finally, the value 15 is inserted between 3 and 19
1000 1500 2000 3000
1000 3 1000 15 2000 19 3000 5 NULL

57 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Q19. Why linked list is called dynamic data structure? What are the advantages of using linked
list over arrays?
Answer : Nov./Dec.-19, Q3 [OU]
Linked List as Dynamic Data Structure
A linked list can grow or shrink its size during the run time. Thus, it is called as dynamic Hey!
Don’t
data structure. In case of a normal data structure say array, it’s size will be fixed through out the escape
program and they consists of only one field. But, linked list consists of two fields i.e., data field from
me
(consists of data) and pointer field (consists of link or the address of the successor element).
Advantages of Linked List over Arrays
1. Linked list is easy to implement.
2. It is a dynamic data structure.
3. It can grow as well as shrink during run time.
Q20. What is Garbage Collection?
Answer : (Model Paper-I, Q6 | Nov./Dec.-18, Q2 [MGU])

Garbage collection is the process of collecting the free memory and inserting them into the free pool. It has
two phase process given as follows,
Don’t Think
1. Initially, it runs through all the list and tags the lists that are being used cur- I am Complex
rently.
2. Next it runs through the memory blocks by collecting, inserting the unused
blocks into the free pool.
This process occurs in the case of overflow, underflow and when the CPU is
idle. Overflow is the process that occurs when a node is to be inserted, but no space
available in the data structure. Underflow is the process that occurs when a node is to be deleted from the empty
list.
Circularly, double linked list is the most preferable data structure for garbage collection. It allows the user
to traverse the list infinitely. Since it is circular and allows to traverse from both the ends.

Publishers and Distributors Pvt. Ltd. 58


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III

P a r t- b E S S AY Q u e s t i o n s a n d A n s w e r s

2.1 RECURSION

2.1.1 Introduction
Q21. What is recursion explain with example? Also write the advantages and disadvantages of
recursion. Model Paper-I, Q15(a)
OR
What is recursion and write an example for recursion?
(Refer Only Topics: Recursion, Example)
Answer : Nov./Dec.-19, Q10(a)(i) [OU]
Recursion
Recursion is the process or technique by which a function calls itself. This function is called recursive function. It
contains a statement within its body, which calls the same function. Thus, it is also called as circular definition. A recursion
can be classified as direct recursion and indirect recursion. In direct recursion, the function calls itself and in the indirect
recursion, a function (f1) calls another function (f2), and the called function (f2) calls the calling function (f1).
Example
Implementation of factorial using direct recursion is,
int fact(int n)
{
int f;
if(n == 0 ¦¦ n = = 1)
f =1;
Keep an eye on me
else
f = n * fact(n – 1); /* Here fact function is calling itself*/
return f;
}
Now, factorial of a number is obtained using this function.
Function to Computer factorial of 3:

Hence the factorial of 3 i.e., fact(3) is 6.


When a recursive call is made, the parameters and return address gets saved on a stack. The stack gets
wrapped when the control is returned back.

59 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Advantages of Recursion
1. It is small, simple and more reliable technique
2.1.2 Recurrence
than other coded versions of the program. Q23. Define Recurrence. Explain generation of
2. It solves the problem in the most general way as fibonacci series using recurrence.
possible.
Answer :
3. It is mainly used to solve the complex problems
that have repetitive structure. Recurrence
4. It is more useful because sometimes a problem Recurrence is a mathematical function that is
is naturally recursive. applied only within the definition of itself.
Disadvantages of Recursion Generating Fibonacci Series Using Recurrence
1. Usage of recursion incurs overhead, since this
technique is implemented using function calls. The recurrence relation for generating Fibonacci
2. Whenever a recursive call is made, some of the series is,
system’s memory is consumed. fibn = fibn–1 + fibn–2.
Q22. What is meant by Recursion? Write a re- A fibonacci number is a positive integer obtained
cursive algorithm to generate Fibonacci by adding its previous two fibonacci numbers. It is
sequence? defined as follows,
Answer : Nov./Dec.-17, Q6(a) [MGU] Z]1. if n = 0
]]
Recursion ]
f (n) = []1, if n = 1
For answer refer Unit-II, Page No. 59, Q.No. 21, ]]
] f ( n – 1) + f ( n – 2 )
Topic: Recursion. \
Recursive Algorithm to Generate Fibonacci Sequence The recursive function to compute n Fibonacci
Input: n numbers is as follows,
Output: Fibonacci sequence upto n unsigned long int fib(unsigned long int n)
Algorithm: Fibonacci (n, a = 0, b = 1) {
1. print a if(n = = 0)
2. if (n < 1) then goto step3 else goto step4 return 1; /* basis */
3. print end and goto step5 if(n = = 1)
4. Fibonacci(n – 1, a + b, a);
return 1; /* basis */
//Here fibonacci function is calling itself
5. End if(n > 1)
Example return fib(n – 1) + fib(n – 2);
Fibonacci series /*recursive call*/
Input: 3 }
Output: Fibonacci sequence Remember me
with concept The recursive function fib( ) is used to compute
Fibonacci(3, 0, 1)
the fibonacci sequence. It considers two special cases n =
print 0
0 and n =1 which are the initial numbers in the fibonacci
if(3 < 1) //condition is not satisfied sequence as the base case of the problem. It computes the
print 0 fibonacci sequence using the recurrence relation fib(n)
Fibonacci(2, 1, 0) = fib(n – 1) + fib(n – 2), For example fib(4) is computed
print 1 as follows,
if(2 < 1) //condition is not satisfied fib(4) = fib(4 – 1) + fib(4 – 2)
print 0
fib(4) = fib(3) + fib(2)
Fibonacci(1, 1, 1)
print 1 fib(3) = fib(3 – 1) + fib(3 – 2)
if(1 < 1) //condition is not satisfied = fib(2) + fib(1)
print 0 fib(2) = fib(2 – 1) + fib(2 – 2)
Fibonacci(0, 2, 1) = fib(1) + fib(0)
print 2
Thus, fib(2) = 2
if(0 < 1)
print end fib(3)= 2 + 1 = 3
End. fib(4)= 3 + 2 = 5
Fibonacci sequence is 0 1 1 2 end \ fib(4) = 5

Publishers and Distributors Pvt. Ltd. 60


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Step 5
2.1.3 Use of Stack in Recursion
The function factorial(2) returns 2 * factorial(1),
Q24. How stack is used in recursion? Explain. since 2 ≠ 1. So, push 2 * factorial(1) onto the
Answer : stack.
Recursion mostly makes use of stack for
implementation. It is the memory area that stores
temporary variables and acts depending upon LIFO
principle. Consider the below recursive function,
int factorial (int n)
{
if(n = = 1)
return n;
else
return n * factorial (n – 1);
}
If n = 5, the function call factorial (5) is made. Step 6
The execution of this call can be explained using stack The function factorial(1), returns 1.
as follows.
Step 1
Push factorial(5) onto the stack.

Step 2
The factorial(5) returns 5 * factorial(4) since,
5 ≠ 1. So, push 5 * factorial(4) onto the stack.
Step 7
Pop 1 and substitute factorial(1) = 1.

Step 3
The factorial(4) returns 4 * factorial(3), since
4 ≠ 1. So, push 4 * factorial(3) onto the stack.

Step 8
Step 4
Pop 2 and substitute factorial(2) = 2.
The factorial(3) returns 3 * factorial(2), since
3 ≠ 1. So, push 3 * factorial(2) onto the stack.

61 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Step 9 Example
Pop 6 and substitute factorial(3) = 6. //Fibonacci Series
int Fibonacci Num(int n)
{
if(n <1)
return = – 1;
if(n = = 1 || n == 2)
Step 10 return 1;
Pop 24 and substitute factorial(4) = 24.
return Fibonacci Num(n – 1) + Fibonacci Num(n – 2);
}
3. Direct Recursion
In direct recursion, the function calls itself
directly.
Step 11
Example
Pop 120. Thus, the function call factorial(5)
returns the value 120. //factorial of a number
int fact (int x)
2.1.4 Variants of Recursion {
Q25. Discuss about various types of recursion. if(x = = 1)
OR return 1;
Briefly describe about the direct recursion, else
indirect recursion and tree recursion with return fact (x – 1) * x;
examples.
}
(Refer Only Topics: Direct Recursion, Indirect
Recursion, Tree Recursion) 4. Indirect Recursion
Answer : May/June-18, Q10(a) [OU] In indirect recursion, the function calls itself
Recursion is categorized into seven different indirectly. For example a function f1 calls another
types. They are as follows, function f2 and the called function f2 calls the calling
1. Linear Recursion function f1.
Linear recursion is a simplest type of recursive Example
algorithm. An algorithm is said to employ linear int fact(int x)
recursion when it makes only one internal recursive
{
call to itself. ie., none of the pending operation contains
a recursive call. All linear recursive algorithms use the if (x < = 1)
following general framework. return 1;
Example else
Factorial is a good example for linear recursion
return (x * temp(x – 1));
int factorial (long n){
}
if(n = =1)
void temp(int x)
return 1;
else {
return (n*factorial (n – 1));} fact(x);
2. Binary Recursion }
An algorithm is said to employ binary recursion 5. Tail Recursion
when it calls itself twice at a time.
Tail recursion can be defined as a function that
Binary recursion is used in data structures like does not have any job to be performed after returning
binary tree for operations such as tree traversal, finding from the recursive call. It returns the last recursive call’s
the height, merging etc. value in the form of function value. The advantage of tail
Examples of Binary recursion are fibonacci series, recursion that the data to be stored while computation
quick sort and merge sort. does not depend upon the count of recursive calls.

Publishers and Distributors Pvt. Ltd. 62


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Example 2.1.5 Execution of Recursive Calls,
In the below code, binarys( ) function is an Recursive Functions
example of tail recursion.
Q26. Explain in brief how recursive calls are
int binarys(int p[ ], int lowv, int highv, int
executed.
keyvalue)
Answer :
{
int mid: Execution of Recursive Calls
if(lowv < = highv) Each time a recursive call is made the values of
reference parameters, local variables, function value and
{
return address are pushed onto the stack. The data that is
mid = (lowv + highv)/2; pushed onto the system stack is maintained in the stack
if(p[mid] = = keyvalue) frame.
return mid; The following are the elements contained in a
else if(keyvalue < p[average]) stack frame.
return Binarys (p, lowv, mid – 1, keyvalue); (i) Reference parameters that the called function
else processes
return binarys(p, mid + 1, highv, keyvalue); (ii) Local variables of calling function
} (iii) Return address
return – 1; (iv) Expression to receive the return value.
} For remaining answer refer Unit-II, Page No.
6. Tree Recursion 61, Q.No. 24.
Tree Recursion can be defined as the recursive The below steps are performed upon the
function in which the recursive call exists in the completion of all recursive calls.
operations that have to be performed after the completion (i) A normal return is executed when the stack
of recursion. Quick sort, merge sort and fibonacci series contains no elements.
algorithm are the examples of tree recursive function.
(ii) When the stack contains elements, pop is
Example
performed on the stack frame to extract the top
The following example of fibonacci series depicts values of the parameters and assign them to their
the tree recursive function variables.
FiboSeries(x) = 0, when x = 0 (iii) The return address is used for finding the location
= 1, wen x = 1 of the call.
= FiboSeries(x – 1) + FiboSeries(x – 2) (iv) The statements are executed from the position
Consider the value of x as 4 where the call is made.
\ FiboSeries(0) = 0 (v) Move to step (i).
FiboSeries(1) = 1 Q27. Write about recursive functions.
FiboSeries(2) = FiboSeries(0) + FiboSeries(1) = 1 Answer :
FiboSeries(3) = FiboSeries(1) + FiboSeries(2) = 2 A function that calls itself is called as recursive
FiboSeries(4) = FiboSeries(2) + FiboSeries(3) = 3 function. In other words, it is said to be a call made to a
The above values are shown in the below figure, specific function from the same function. This concept is
FiboSeries(4)
called recursion. If proper care is not taken then it ends
in an indefinite loop. Consider the below example.
FiboSeries(3) FiboSeries(2) A factorial is a classic recursive algorithm. A simple
mathematical definition of the factorial operation is,
fact(0) = 1
FiboSeries(2) FiboSeries(1) FiboSeries(1) FiboSeries(0) fact(n) = n * fact(n –1)
factorial is commonly expressed by exclamation
mark (!)
FiboSeries(1) FiboSeries(0)
Calculate the Factorial of 3
7. n-ary Recursion and Permutations
1. fact(3) = 3 * fact(2)
Recursion is called as n-ary recursion when n
2. fact(2) = 2 * fact(1)
is the parameter that is used in a function and when
it is not a constant. They are mostly used to generate 3. fact(1) = 1 * fact(0)
combinatorial objects like permutations. 4. fact(0) = 1

63 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
We know that fact (0) = 1 Step 1
fact(1) = 1 * fact(0) = 1 * 1 = 1 Shift one disk from source to destination.
fact(2) = 2 * fact(1) = 2 *1 = 2
fact(3) = 3 * fact(2) = 3 * 2 = 6
Example
Consider the factorial algorithm,
Algorithm factorial (n)
if(n = = 0) Step 2
return 1 Shift one disk from source to auxiliary.
else
return (n* factorial n – 1)) //General case
end if
end factorial
Q28. Explain Tower of Hanoi using recursion.
Write the algorithm and draw the tree
representation of recursive calls of the
algorithm for 3 disks. Step 3
Answer : (Model Paper-I, Q16 | June/July-19, Q10(a) [OU]) Shift one disk from destination to auxiliary.
Towers of Hanoi Problem
Towers of Hanoi is a classical
example of recursion problem. It is
easier, efficient and do not make use of Hey!
complex data structures. Don’t
In this problem, there are three escape
from
towers named as source, auxiliary and me
destination. The source tower consists of Step 4
three disks of different sizes, where each disk rest on the Shift one disk from source to destination.
one just larger than it. This is shown in the figure below,

Step 5
The task is to move all the three disks from source Shift one disk from auxiliary to source.
to destination without violating the following rules.
1. At a time, only one disk may be moved.
2. Larger disk should not be placed on top of a
smaller disk.
3. For the purpose of intermediate storage of disks,
only one auxiliary tower should be used.
Towers of Hanoi Solution for Three Disks
Step 6
Start
Shift one disk from auxiliary to destination.
The source tower consisting of three disks.

Publishers and Distributors Pvt. Ltd. 64


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Step 7
2.1.6 Iteration Versus Recursion
Shift the remaining disk from source to
destination. Q29. Derive and solve the recurrence relation
for the towers of hanoi problem.
Answer :
Recurrence Relation for Towers of Hanoi Problem
Let the minimum number of moves needed to
solve the problem be T(N) where N is the number of
disks.
Thus, the destination consists of three disks In the function call Hanoi if N = 0, no disks are
satisfying the given rules. transferred. For N > 0, two recursive calls are made to
transfer N – 1 disks, and another to transfer the largest
Algorithm for Towers of Hanoi Problem
disk from source needle to destination needle.
Algorithm TowersOf Hanoi(n, source, auxiliary,
Thus, the recurrence relation for the tower of
destination)
Hanoi problem is given as,
/* n is the number of disks, source is
the tower from which disks are to be
transferred, destination is the tower to
which disks are to be transferred and Solution of Towers of Hanoi Problem
auxiliary is a temporary tower*/ The recurrence relation for the Towers of Hanoi
if(n= =0) problem can be solved by repeatedly substituting T(K)
occurring on the right hand side until T-disappears. This
then exit( ); is referred to as a closed form solution.
else T(N) = 2.T(N – 1)
/* Move n–1 disks from source to = 2.(2.T(N – 2) + 1) + 1
auxiliary with destination as temporary
tower*/ = 22 T(N – 2) + 2 + 1

TowersOfHanoi(n–1, source, destination, = 22(2.T(N – 3) + 1) + 2 + 1


auxiliary); = 23.T(N – 3) + 22 + 2 + 1
move the disk from source to destination; In the kth step,
/*Move n–1 disks from auxiliary T(N) = 2KT(N – K) + 2(K – 1) + 2(K – 2) +.....+ 23 + 22 + 2 + 1
to destination with source as
When, K = N, we get,
temporary tower*/
T(N) = 2NT(N – N) + 2(N – 1) + 2(N – 2) + ..... + 23 + 22 + 2 + 1
TowersOfHanoi(n – 1, auxiliary, source,
destination); = 2NT(0) + 2(N – 1) + 2(N – 2) + ..... + 23 + 22 + 2 + 1

end = 2N.0 + (2N – 1)

Tree Representation of Towers of Hanoi = 2N – 1


Hanoi (3, S, A, D) = O(2N).
Therefore, the time complexity of towers of Hanoi
problem is O(2N).
Hanoi (2, S, D, A) Hanoi (2, A, S, D)
Q30. Write about Iteration Versus Recursion.
Answer :
Hanoi (1, S, A, D) Hanoi (1, D, S, A) Hanoi (1, A, D, S) Hanoi (1, S, A, D) Iteration Versus Recursion
Recursion is a top down approach whereas
S→D S→A D→A S→D A→S A→D S→D Iteration is a bottom-up approach. In Recursion, every
Figure: Tree Representation of Recursive Calls problem is divided into sub-problems among which it
chooses any one step and postpones the other steps. In
In the above figure, number of disks n = 3. It takes iteration, the process starts with the known condition
7 moves for the three disks to reach the destination tower. and then it finds the solution in step-by-step manner.

65 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Limitations of Recursive Algorithms (a) Insertion
1. Recursion is not supported by most of the Adds new item at rear end of queue.
programming language such as FORTRAN,
Insertion operation performs the following actions,
COBOL. Therefore, the recursive mathematical
function will be implemented by using iterative 1. If rear == MAX – 1 i.e., queue is full, then
methods. prints a message that ‘queue is full’ and no
2. Recursive mathematical functions can be new element can be added to queue.
easily implemented but they involve additional 2. Otherwise, increments rear by 1 and in-
execution time and memory. serts new element at rear position.
3. A recursive function is called from itself or from (b) Deletion
outside. To check whether the recursive function
Deletes an item from front end of queue.
is working properly or not, a return address
should be provided in a specific order (here, the Queues are implemented sequentially using an ar-
return address consists of output). ray. Two variables ‘front’ and ‘rear’ hold the position of
Limitations of Iterative Methods first and last elements in queue respectively. Queue can
have 0 to MAX–1 elements where MAX is the size of
1. Iterative is complex and difficult to read and
array.
understand.
2. The iterative methods require loop statements Initially, when queue is empty, front = rear = –1.
along with complex logic. Deletion operation performs the following actions,
3. The iterative method is executed in step-by-step 1. If the queue is empty which is given by
manner. Therefore, it contains huge length of front = –1, then prints a message that “dele-
code. tion is not possible”.
2.2 Queues 2. Otherwise, retrieves the front element and
then increments front by 1.
2.2.1 Concept, Primitive Operations Example
Q31. What is queue? Explain primitive opera- Consider the following sequence of insertion
tions on queue. Model Paper-I, Q15(b) and deletion operations.
OR Let the size of queue be 5.
Initially front = – 1 and rear = – 1.
Explain the queue operations with a pro-
1. insert(10)
gram code and examples.
This increments rear by 1 and inserts 10
Answer : Nov./Dec.-17, Q10(a) [OU]

Queue Don’t Think


I am Complex
A queue is an ordered
collection of items in which 2. insert(20)
items may be inserted at one end
This increments rear by 1 and inserts 20.
(known as rear end) and may be
deleted from other end (known
as front end).
Queue is also known as FIFO (first in first out)
structure because the element which is inserted first front = –1,
will be deleted first. Diagrammatically it is shown as,
rear = 1
Deletion Insertion
3. insert(30)
This increments rear by 1 and inserts 30
a b c d
Queue

Front Rear

Primitive Operations
The basic operations performed on queues are in- front = –1,
sertion and deletion. rear = 2

Publishers and Distributors Pvt. Ltd. 66


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
4. delete(10) arr[frontend] = el;
This deletes an item from queue by incrementing }
front by 1. template <class tmp>
void queue<tmp> :: remove( )
{
5. delete(20) tmp el;
This increments front by 1 and deletes the item from if (frontend == –1)
front. {
cout<<“Underflow occured\n”;
return;

}
6. delete(30)
el = arr [rearend];
Front is incremented to 2 and 30 is deleted. if (frontend == rearend)
frontend = rearend = –1;
else
rearend ++;
Program cout <<“The deleted element is:” <<el;
#include<iostream.h> }
#include<conio.h> template<class tmp>
#include<stdlib.h> void queue <tmp> ::show( )
template<class tmp> {
class queue int i;
{ if (frontend == –1)
{
int rearend, frontend, n;
cout <<“Queue is empty\n”;
tmp arr[20];
return;
public:
}
queue (int num) for (i=rearend; i<=frontend;i ++)
{ cout << arr [i] <<“ ”;
frontend = rearend = –1; cout <<“\n”;
n = num; }
} void main( )
void insert( ); {
void remove( ); int c, n;
void show( ); clrscr( );
}; cout <<“Enter the size of the queue:”;
template <class tmp> cin >>n;
queue<int> que (n);
void queue<tmp> :: insert( )
while (1)
{
{
tmp el;
cout <<“\n Menu\n”;
if(rearend >= n–1) cout <<“1.Insert\t 2.Pop\t 3. Display \t 4.Exit\n”;
{ cout <<“Enter your choice|”;
cout <<“Overflow occured\n”; cin >> c;
return; switch(c)
} {
cout <<“Enter the element:”; case 1:
cin >>el; for(int i=1;i<=n;i++)
if (rearend == –1) {
frontend = rearend = 0; que.insert( );
else }
frontend ++; break;

67 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
case 2: Step2: If the queue is empty then increment rear by 1
que.remove( ); i.e., rear = rear + 1.
break;
Step3: Finally, insert the element into queue by initial-
case 3:
izing Q[rear] = item.
que.show( );
break; Step4: Return
case 4: (ii) Deletion
exit(0); This element deletes an item from front end of
break; queue.
default: Algorithm
cout<<“Invalid option\n”;
The algorithm to delete an element from queue
break;
is as follows,
}
} Step1: Check whether the queue is empty by using the
following condition,
}
Output (i) If front = – 1
(ii) Print “Queue empty”
(iii) return.
Step2: If queue is full, then set,
(i) item = Q [front] and
(ii) Q[front] = 0.
Step3: Next, perform the following actions,
(i) If front = rear then
(ii) Initialize front = – 1 and rear = – 1
(iii) Goto step 5.
Step4: Otherwise, increment front by 1 i.e.,
front = front + 1
Step5: return(item).
Q32. Explain various operations performed
on queue with suitable algorithms. 2.2.2 Abstract Data Type,
Representation Queues Using Arrays
Answer :
The two basic operations performed on queue are, Q33. What is a queue? Give the ADT for a queue.
(i) Insertion Answer : May/June-18, Q10(b)(i) [OU]

(ii) Deletion. Queue


(i) Insertion For answer refer Unit-II, Page No. 66, Q.No. 31,
This operation adds a new element at rear end of Topic: Queue.
queue. ADT for a Queue
Algorithm The queue abstract data type consists of data type
The algorithm to insert elements into queue is as definitions and queue operations. The queue ADT type
follows, definitions define two structures, namely node structure
Procedure Q(Q, front, rear, MAX, item) and head structure.
Step1: Check whether the queue is full by using the fol- The node structure contains two pointers in which
lowing, a pointer of type void is used to point data and another
link pointer is used to refer the next element in the queue.
(i) if(rear>max) then
The head structure contains two pointers front and rear
(ii) print “Queue overflow” that point to front and rear end of the queue respectively.
(iii) Return. The operations on the queue are as follows,

Publishers and Distributors Pvt. Ltd. 68


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
create( ) : It allocates a node for the queue header, Q34. Discuss about,
and returns the reference of the queue (a) Create
head. (b) Enqueue
destroy( ) : It deletes all the elements of a queue and (c) Dequeue.
makes each node free. Answer :
front( ) : It returns reference of the element stored (a) Create
at the front end of a queue. The create operation on queue allocates a node
rear( ) : It returns reference of the element stored for the queue header. The pointers rear and front are
at the rear end of a queue. set to NULL and the counter variable is assigned with
value ‘0’. If the allocation is done then create function
enqueue ( ) : It checks for the availability of memory returns the address of the queue head, otherwise returns
to insert new node at the rear end of null indicating overflow.
queue and returns true if memory is
QUEUEADT * create (void)
available, otherwise returns false.
{
dequeue( ) : It returns true when deletion ends
QUEUEADT * queueadt;
successfully otherwise returns false.
//malloc is used to allocate memory from heap
empty( ) : It checks whether the queue is empty. If queueadt = (QUEUEADT*) malloc size of
it is empty returns true otherwise returns (QUEUEADT));
false.
if (queueadt)
full( ) : It checks whether the queue is full. If it is {
full returns true otherwise returns false. queueadt –> front = Null;
size( ) : It returns the total number of elements queueadt –> rear = Null;
stored in a queue. queueadt –> count = 0;
The Queue ADT structure is given below, }
//Queue ADT type definitions return queueadt;
}
typedef struct node
(b) Enqueue
{
The insertion of an element into the queue is
void *data ptr; known as enqueue. The enqueue operation is very simple.
struct node * next; It first creates a node, if the memory is available then
inserts the new element at the rear end of the queue. If
} NODE; the insertion was successful, then it returns true otherwise
typedef struct returns false.
{ bool enqueue (QUEUEADT * queueadt,
void * datapointer)
NODE *front;
{
NODE *rear; NODE * newNode;
int count; if (!(newNode = (NODE *) malloc
} QUEUEADT; // operations on Queue (size of (NODE))))
return false;
QUEUEADT*create (void);
newNode –> data newNode = datapointer;
QUEUEADT*destroy (QUEUEADT *queueadt); newNode –> link = NULL;
bool front (QUEUEADT *queueadt, void ** datapointer); //insertion into emptyqueue.
bool rear (QUEUEADT *queueadt, void ** datapointer); if (queueadt –> count = = 0)
bool enqueue (QUEUEADT *queueadt, queueadt –> front = newNode;
void * datapointer); //insertion into non-emptyqueue
else
bool dequeue (QUEUEADT *queueadt,
void ** datapointer); queueadt –> rear –> link = newNode;
(queueadt –> count) + +;
bool empty (QUEUEADT * queueadt);
queueadt –> rear = newNode
bool full (QUEUEADT *queueadt); return true;
int size (QUEUEADT *queueadt); }

69 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
(c) Dequeue int QueueAdt::is_empty( )
The deletion of an element from a queue is {
known as dequeue. The dequeue operation first checks if(front_queue==rear_queue)
for the availability of data in the queue. If there is data return 1;
in the queue, it deletes the data then it sends the address else
of the deleted element to calling function through return 0;
reference parameter and adjusts the pointer. Then after, }
it decrements the count variable. On successful deletion int QueueAdt::is_full( )
of an element, it returns true. Otherwise, it returns false. {
bool dequeue (QUEUEADT * queueadt, if(rear_queue==max_queue–1)
void ** datapointer) return 1;
{ else
NODE * deleteNode; return 0;
}
if(!queueadt –> count)
void QueueAdt::add(int elem)
return 0;
{
* element = queueadt –> front –> data ptr; if(!is_full( ))
deleteNode = queueadt –> front; Queue[++rear_queue]=elem;
if(queueadt –> count = = 1) queue_size++;
queueadt –> rear = queueadt –> }
front = NULL; //deleting datapointer int QueueAdt::delet( )
else {
queueadt –> front = queueadt –> front –>link; if(!is_empty())
(queueadt –> count) – –; {
free (deleteNode); queue_size– –;
return 1; return(Queue[++front_queue]);
}
}
else
Q35. Write a C++ program to implement queue return 0 ;
ADT. }
Answer : Nov./Dec.-19, Q8(a) [MGU] int QueueAdt::getfront( )
Program {
#include<iostream> if(!is_empty( ))
#include<conio.h> return(Queue[front_queue+1]);
using namespace std; else
class QueueAdt return 0 ;
{ }
private: int main()
int rear_queue,front_queue; {
cout<<“The deleted elements are:\n”;
int Queue[50];
QueueAdt qa;
int max_queue;
qa.add(4);
int queue_size;
qa.add(7);
public: qa.add(10);
QueueAdt( ) cout<<qa.delet( )<<endl;
{ qa.add(13);
queue_size=0; cout<<qa.delet( )<<endl;
max_queue=50; qa.add(16);
rear_queue=–1; cout<<qa.delet( )<<endl;
front_queue=–1; return 0;
} }
int is_empty( ); Output
int is_full( );
void add(int elem);
int delet( );
int getfront( );
};

Publishers and Distributors Pvt. Ltd. 70


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Q36. Discuss in detail about array implementation 1. Create Queue
of queue ADT. The implementation for creating a queue is as
OR follows,
QUEUE* create-que (int max)
Explain the operations of Queues using
Arrays. {
QUEUE* queue;
Answer : May/June-19, Q6(a) [MGU]
queue = (QUEUE*) malloc(size of (QUEUE));
Array Implementation of Queue ADT if(queue)
The array implementation of Queue ADT can {
be done by using indexes. This type of implementation // head structure is created and queue is allocated
requires the following two changes in the data structure
queue –> queArray = (void**) calloc
for the queue head.
(max, size of(void*));
(a) Storage of address of the queue array which is queue –> count = 0;
allocated from the dynamic memory. queue –> front = – 1;
(b) Storage of maximum number of elements in the queue –> rear = – 1;
array. queue –> max = max;
ADT operations for array implementation of }
queue are as follows, return queue;
1. Create queue }
2. Destroy queue This implementation allocates memory for a
queue head structure and the array in dynamic memory.
3. Enqueue
Then, it returns the address of head structure to the caller.
ple

4. Dequeue It returns a null pointer if sufficient memory for the queue


Very Sim
ex
pl
m

structure is not available.


Co

5. Queue count
t
g
in

bu
ok

2. Destroy Queue
Lo

6. Queue front
The implementation for destroying the queue is
7. Queue rear as follows,
8. Full queue QUEUE* destroy-que(QUEUE* queue)
9. Empty queue. {
The definitions of queue ADT and prototype int location = queue –> front;
declarations are shown below, if (queue)
typedef struct {
While(queue –> count ! = 0)
{
{
void** queArray; free(queue → queArray [location++]);
int max; queue –> count – – ;
int count; if(location = = queue –> max)
int front; location = 0;
}
int rear;
free(queue –> queArray);
} QUEUE;
free(queue);
QUEUE* create-que (int max); }
QUEUE* destroy-que (QUEUE* queue); return NULL;
bool enqueue(QUEUE* queue, void* elem ptr); }
Queue is destroyed after freeing the array and
void* dequeue (QUEUE* queue);
load structure and returning a null pointer.
void* queCount (QUEUE* queue); 3. Enqueue
void* queFront (QUEUE* queue); The implementation for enqueue operation is as
int queRear (QUEUE* queue); follows,
bool fullQueue (QUEUE* queue); bool enqueue(QUEUE* queue, void* elemPtr)
bool emptyQueue (QUEUE* queue); {

71 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
if(queue –> count = = queue –> max) 6. Queue Front
return false; The implementation of queue front is as follows,
(queue –> rear) + + ; void* queFront(QUEUE* queue)
if(queue –> rear = = queue –> max) {
// wrap to the first element if(!queue –> count)
queue –> rear = 0; return NULL;
return queue –> queArray [queue –> front];
queue –> queArray [queue –> rear] = elemPtr;
}
if(queue –> count = = 0;
Its implementation is performed parallel to dequeue
{ operation with one dissimilarity that the queue status re-
//Insert elements into null queue mains same.
queue –> front = 0; 7. Queue Rear
queue –> count = 1; The implementation of queue rear is as follows,
} void* queRear (QUEUE* queue)
else {
(queue –> count) + +; if(!queue –> count)
return true; return NULL;
} return queue –> queArray [queue –> rear];
}
This implementation first determines the array
element to store the data pointer. It then determines This implementation returns a pointer to the data
whether the queue is full, by comparing the queue count at the queue rear keeping the queue data same.
to maximum queue size. The queue will be full if this 8. Full Queue
comparison is equal. The element to be inserted is added This implementation for full queue is as follows,
to the rear index. Wrap the element to queue’s first ele- bool fullQueue (QUEUE* queue)
ment if rear is at the last element. {
4. Dequeue return(queue –> count = = queue –> max);
}
The implementation for dequeue operation is as
This implementation tests the count to maximum
follows,
queue size. The queue is found to be full if they are equal.
void* dequeue (QUEUE* queue)
9. Empty Queue
{ The implementation for empty queue is as fol-
void* dataPtrOut lows,
if(! queue –> count) bool emptyQueue (QUEUE* queue)
return NULL; {
dataPtrOut = queue –> queArray [queue –> front]; return (queue –> count = = 0);
(queue –> front) + +; }
if (queue –> front = = queue –> max) This implementation tests the count to null. The
// queue front is wrapped to first element queue is found to be empty if they are equal.
queue –> front = 0; 2.2.3 Circular Queue, Double-Ended
if(queue –> count = = 1) Queue
// deletes element in the queue
Q37. Discuss on Circular Queue with examples.
queue –> rear = queue –> front = – 1;
(queue –> count) – –; Nov./Dec.-18, Q6(a) [MGU]
return dataPtrOut; OR
} Explain implementation of circular queue
This implementation deletes data at the queue using arrays.
front and returns the same to the calling function. Answer : May/June-18, Q10(b)(ii) [OU]
5. Queue Count Circular Queues Don’t Think
The implementation for queue count is as follows, Circular queue is a variant I am Complex
int queueCount(QUEUE* queue) of a queue in which elements are
{ stored in circular manner. These
return queue –> count; queues are implemented using
} arrays. The main purpose of using
The queue count implementation returns the circular queue is to overcome the
number of elements present in the queue. problem of unutilized space present in linear queue.

Publishers and Distributors Pvt. Ltd. 72


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Similar to linear queues, circular queues, also insert the (b) Dequeue(Deletion) Operations
item from rear end and delete the item from the front end. Algorithm Dequeue
Unlike in linear queue (where no more elements can be Input
added once the end of the array is marked) in circular A circular queue containing elements called items
queue elements can be added eventhough end of array with two pointers namely FRONT and REAR
have been reached. Data Structure
Now, consider an array cqueue, that contains ‘k’ An array ‘A’ for representing circular queue
elements in which cqueue[1] comes after cqueue[k] in Output
the array. A linear queue can be transformed to circular Deletes the elements from queue
queue when last room comes just before the first room. Step1: Check whether queue is full or empty using statements.
If(FRONT = = 0) then
Step2: Print “Deletion cannot be done as queue is empty”.
Step3: Exit
Step4: Go to else
Step5: Perform initialization ITEM1 = A[FRONT]
Step6: If(FRONT = = REAR) then
Initialize FRONT with 0
FRONT = 0
Figure: Circular Queue
Initialize REAR with 0
The two primitive operations performed on
REAR = 0
circular queues are,
Step7: Go to else
(a) Enqueue(insertion) operation Step8: FRONT = (FRONT MOD LENGTH ) + 1
(b) Dequeue(deletion) operation. Step9: End if
(a) Enqueue(Insertion) Operations Step10: End if
Algorithm Enqueue Step11: Stop
Example
Input
#include<stdio.h>
An ITEM(element) which should be inserted on #define max 3
the circular queue.
int q[10],front=0,rear=–1;
Data Structure void main()
An arrays ‘A’ for representing circular queue with {
two pointers namely FRONT and REAR int ch;
Output void insert();
The given input called ITEM(element) inserted void delet();
on circular queue. void display();
Step1: Check whether queue is full or empty using the clrscr();
following condition, printf(“\nCircular Queue operations\n”);
printf(“1.insert\n2.delete\n3.display
If(FRONT == 0)
\n4.exit\n”);
Step2: Initialize FRONT with 1 while(1)
Front = 1 {
Step3: Initialize REAR with 1 printf(“Enter your choice:”);
REAR = 1 scanf(“%d”,&ch);
Step4: A[FRONT] = ITEM 1 switch(ch)
{
Step5: Go to else
case 1: insert( );
Step6: Next = (REAR mod LENGTH) + 1 break;
Step7: If(next ¹ FRONT) then case 2: delet( );
Step8: REAR = Next break;
Step9: A[REAR] = ITEM case 3:display( );
break;
Step10: Go to else
case 4:exit( );
Step11: Printf “Insertion cannot be done as queue is full”
default:printf(“Invalid option\n”);
Step12: End if }
Step13: End if }
Step14: Stop }

73 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
void insert() int i,j;
{ if(front==0&&rear== –1)
int x; {
if((front==0&&rear==max–1)||
printf(“Queue is underflow\n”);
(front>0&&rear==front–1))
getch();
printf(“Queue is overflow\n”);
exit();
else
{ }
printf(“Enter element to be insert:”); if(front>rear)
scanf(“%d”,&x); {
if(rear==max–1&&front>0) for(i=0;i<=rear;i++)
{ printf(“\t%d”,q[i]);
rear=0; for(j=front;j<=max–1;j++)
q[rear]=x;
printf(“\t%d”,q[j]);
}
printf(“\nrear is at %d\n”,q[rear]);
else
{ printf(“\nfront is at %d\n”,q[front]);
if((front==0&&rear==–1)||(rear!=front–1)) }
q[++rear]=x; else
} {
} for(i=front;i<=rear;i++)
} {
void delet()
printf(“\t%d”,q[i]);
{
}
int a;
printf(“\nrear is at %d\n”,q[rear]);
if((front==0)&&(rear==–1))
{ printf(“\nfront is at %d\n”,q[front]);
printf(“Queue is underflow\n”); }
getch(); printf(“\n”);
exit(); }
} getch();
if(front==rear) }
{
Output
a=q[front];
rear=–1;
front=0;
}
else
if(front==max–1)
{
a=q[front];
front=0;
}
else a=q[front++];
printf(“Deleted element is:%d\n”,a);
}
void display()
{

Publishers and Distributors Pvt. Ltd. 74


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Q38. Explain in detail about deque. Step3: If deque is not empty and if FRONT is at extreme
Answer : right
Deque Go to else
A deque is an ordered list of elements in which Step4: If(FRONT = L) or (FRONT = 0) then
elements can be pushed and popped from both front and Step5: Head = 1
back ends. Thus, a deque is also called a “double-ended
queue”. Below figure gives structure of a deque. Step6: Go to else
Step7: Perform the following action if front is at
intermediate position
head = FRONT – 1
Step8: End If
Step9: If(head = REAR)
Figure: Deque Structure
Step10: Print “Insertion cannot be done as deque is full”
From above figure, it is clear that, a deque is a
combination of queue and stack. A queue is simulated Step11: Exit
when elements are pushed at the back end, but popped Step12: Go to else
at its front end. A stack is simulated when elements are
pushed and popped both at the front and back ends. Step13: Perform the following action to push the item
Queue Vs Deque on deque
1. A queue is a FIFO structure, whereas a deque is FRONT = Head
a combination of FIFO and LIFO structures. Step14: A[FRONT] = ITEM1
2. In a queue, elements can be pushed only at the
back end, whereas in a deque elements can be Step15: END IF
pushed from both ends. Step16: END IF
3. In a queue, elements can be popped only from Step17: STOP
the front end, whereas in a deque elements can
be popped from both ends. (ii) POP( ) Operation
Operations on Deque This operation removes an element from FRONT
end of deque.
The various operations that are performed on
deque are as follows, Algorithm for POP Operation on Dequeue
(i) Push(ITEM) For answer refer Unit-II, Page No. 73, Q.No. 37,
Topic: Dequeue(Deletion) Operations.
(ii) POP( )
(iii) Inject(ITEM) Operation
(iii) Inject(ITEM)
This operation inserts an element called ITEM at
(iv) Eject.
REAR position of dequeue.
(i) Push(ITEM)
Algorithm for Performing Inject Operation on
This operation inserts/adds an ITEM(element) at Dequeue
the FRONT end of deque.
For answer refer Unit-II, Page No. 73, Q.No. 37,
Algorithm for PUSH Operation on Deque Topic: Enqueue(Insertion) Operations.
Input (iv) Eject( ) Operation
An element called ITEM that should be inserted This operation removes an element called ITEM
at the front end of deque. from REAR end of deque.
Data Structure Algorithm for Implementing Eject( ) Operation on
A circular array A for representation of deque. Deque
Output Algorithm Eject_Deque
A newly inserted item on deque Input
Step1: Check whether the FRONT pointer is at extreme A deque containing elements(ITEMS).
left using following statement Data Structure
If(FRONT = 1) then A circular array ‘A’ for representing a deque.
Step2: Initialize Output
Head = L (L is the length) Deletes an item from rear end.

75 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Step1: Check whether queue is full or empty using the Q40. What is queue? And explain about circular
following statement, queue and double ended queue.
If(FRONT = = 0) then Answer : (Model Paper-II, Q15 | Nov./Dec.-19, Q10(a)(ii) [OU])
Step2: Print “Deletion cannot be done as Deque is Empty” Queue
Step3: Exit For answer refer Unit-II, Page No. 66, Q.No. 31,
Step4: Go to else Topic: Queue.
Step5: If deque contain single element i.e., Circular Queue
If(FRONT = = REAR) then For answer refer Unit-II, Page No. 72, Q.No. 37.
Step6: Initialize
Double Ended Queue
ITEM 1 = A[REAR]
For answer refer Unit-II, Page No. 75, Q.No. 38.
Step7: FRONT == REAR = 0
Step8: Go to else 2.2.4 Applications of Queues
Step9: If REAR end is at extreme left i.e., Q41. Explain the applications of Queues.
If(REAR == 1] then Answer :
Step10: ITEM 1 = A[REAR] Various applications of queues are as follows,
Step11: Initialize rear with length 1. Josephus Problem
REAR = L
Josephus problem is solved by making use of
Step12: Go to else circular queue. This problem can be illustrated with the
Step13: If rear is at extreme right i.e., help of the following example,
If(Rear = L) then Consider a group of soldiers are surrounded by
Step14: Initialize an enemy force. Such that the victory can’t be achieved
since there is only one horse available to escape. Here,
ITEM1 = A[REAR] the soldiers are grouped to form a circle and a number
Step15: Initialize the following ‘M’ is picked to start the count as well as the name of
any soldier is picked using a hat. The process starts with
REAR = 1
particular soldier by counting around the circle in clock
Step16: Else if rear is at intermediate position then wise direction. If the count has reached to M then that
Go to else particular soldier is removed from the circle and the
process continues by starting it from the next soldier.
Step17: Initialize
Therefore, this process is repeated until one soldier is
ITEM 1 = A[REAR] left out in the circle. The last soldier who is left will have
Step18: Decrement rear by 1 i.e., a chance to escape by taking the horse.
REAR = REAR – 1 The problem should determine the following.
Step19: End IF (i) The number ‘M’
Step20: End IF (ii) Whether the count begins in clockwise or
Step21: End IF anticlock wise directions.
Step22: End IF (iii) From which soldier the process should be started.
Step23: Stop. (iv) The order should be specified from where the
Q39. Write short note on: soldiers are removed from the circle.
(i) Recursion (v) Which soldier has to be escaped?
(ii) Double-ended queues. The given input for a problem is number M and a
Answer : May-18, Q6(b) [MGU] group of names of soldiers. It begins by considering the
direction i.e., in clockwise direction and also the name
(i) Recursion of the soldier from where to start. End of the input is the
For answer refer Unit-II, Page No. 59, Q.No. 21. last input line that consists of string end for denoting the
(ii) Double-ended Queues end of input. The output of the program should print the
names of the soldiers who were removed in an order and
For answer refer Unit-II, Page No. 75, Q.No. 38. the last soldier who had escaped.

Publishers and Distributors Pvt. Ltd. 76


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Example (e) Another job is added to s, if it satisfies the
Consider the value of Numbers N = 3 and group following conditions.
of soldiers P, Q, R, S, T, U. The count is given as 3, so 1. Searching is performed to find the job which
the process starts from P and R is removed first. Then the has next maximum profit.
process starts from S and U is removed. Next the process 2. Check whether this job is feasible with the
starts from P and S is removed (since R is removed union of s.
earlier). The process starts from T and Q is removed. 3. If it is feasible then go to step (e) and
Therefore, T and P are left. The process starts from T continue, otherwise go to step (4).
and T is removed. Hence, P is the last soldier who has 4. Searching is performed to find the job that
to escape. has next maximum profit and go to step (b).
The above problem is shown by using a circular (f) End if there is no requirement for addition of jobs.
list. Each and every node is represented as a soldier in
Example
order to solve the problem. Any node can be visited from
another node by performing the count around the circle Consider the five jobs along with its profits (pf1,
in clock wise direction. A soldier that is removed from pf2, pf3, pf4, pf5) = (30, 25, 20, 15, 10) and the maximum
the circle can be shown by a node that is deleted from deadlines are (dl1, dl2, dl3, dl4, dl5) = (2, 3, 1, 3, 3)
a list. When there is only single node in the list then it respectively.
will be the output. The maximum number of jobs that can complete
their execution before deadline is given by,
Algorithm
Min (m, max deadline (dlj)) = Min (5, 3) = 3
The algorithm for the above problem is as given
below, Therefore, the possibility of completing the jobs
are three. These three jobs can be completed in 3 units
(i) Assume M as the total number of persons. which is shown below,
(ii) Start with the first person present in the list.
Time Profit (pf) Job (j)
(iii) Now, add each and every person to the queue.
0–1 30 1
(iv) While
1–2 25 2
count (N–1) persons in the queue;
2–3 15 3 cannot be accommodated
Name of Nth person is printed;
2–3 10 4
Nth person is removed from the queue;
Total profit = 65
(v) Print one person’s name who is left in the list.
In this example 1 is completed in the first unit
2. Job Scheduling
of time and gained a profit of 30. Then for the second
Job scheduling is the process of scheduling the unit of time, job 2 is completed and gained a profit of
jobs in the specific order in which they are to be executed. 25. Job 3 is not completed since it is not available for
Consider a list containing ‘m’ jobs that are needed to be the third unit of time. So, the job 4 is completed with a
scheduled. Each job ‘j’ is assigned with a deadline. profit of 15 at third unit of time. The deadline for job 5
dlj ≥ 0 and a profit pfj ≥ 0 respectively. Each job is 3 which is already completed. Hence, three jobs i.e.,
‘j’ is said to be profitable when it is finished before its job 1, job 2, and job 4 are completed before its deadline
meets and completed by a profit of 65.
deadline. So, a feasible solution that can be obtained is
the total sum of all profits. 3. Simulation
Simulation deals with modeling real-time
The optimal solution and the job’s feasibility problem in the form of a computer program under the
are obtained by finding the subset ‘s’ in such a way that control of various parameters.
every job belongs to subset ‘s’ must finish its execution An advantage of simulation is that it allows to
before it meets the deadline. The feasible solution ‘s’ is experiment the dangerous operations (like, military, etc)
the sum 1 (total of all the profits of s). virtually instead of actual field test.
Any process, that is to be simulated is called a
The algorithm that illustrates the process of
system. System is a collection of interconnected objects,
finding the subset s is given below: with many inputs and produces at least a single output.
(a) The objective function of the optimization Simulation models are decided based upon the
measure is Spfj × j ∈ s. changes in state of a system. They are of two types :
(b) This measure is used for the next job to include time-driven and event-driven.
In time driven simulation, state of a system
in it which can be an increment i.e., Spfj × j ∈ s.
changes with the change in time.
(c) Initially, initialize s = f, Spfj = 0, j ∈ s. And in event driven simulation, state of a system
(d) Now, select a job that has maximum profit and changes when a new event occurs in the system or gets
add the job to the subset s. terminated.

77 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Example
Consider a ticket reservation counter, here, we
have two kinds of tickets, T1, T2 and two counters C1
and C2 for the customer to purchase respective ticket.
Let us assume the time required to issue ticket T1 Figure: Node
and T2 are t1 and t2 respectively. Example

Figure: Linked List


Operations on Linked List
... . . .. . .. . . . . . . ... ...... ..... . . . . .. . . . . . .
.. .. .. ... .. .. .. .. .. .. .. .. .. ........ ......... ...... ... .. ... .. .. .. ... .. .. .. .. The basic operations that can be performed on
.... .... .. .. .. .. .. .. .. .. .. .. .... .. ..................... .... .. .. .. .. .. .. .. ..
linked list are,
(i) Traversing the list
(ii) Inserting a node (at the beginning of the list, at
the end of the list and at a specific position on
the list)
Correction 1: Q1 and Q2 are two queues for counters (iii) Deleting a node from the list (from the begin-
C1 and C2 respectively, two models are proposed for ning, from the end and from any specific posi-
selling tickets. tion in the list)
Model 1 (iv) Modifying the data value of any node.
1. Both the tickets T1 and T2 can be issued by any Advantages
counter. 1. Linked list is easy to implement.
2. To visit the ticket counter, the customer will join 2. It is a dynamic data structure.
the queue which has less number of people. If 3. It can grow as well as shrink during run time.
both the queues have equal number of people
Disadvantages
then customer will join in the first queue Q1 of
counter C1. 1. It requires extra memory space to store pointers.
Model 2 2. It can be traversed only in one direction.
1. In this, both the counters are fixed in issuing a 3. It is difficult to sort its elements.
particular ticket that is T1 will be issued only by 4. It requires huge amount of time for accessing
counter C1 and T2 will be issued only by counter C2. each element.
2. When the customer visits the ticket counter, queue Q43. List out the commonly used terms related
Q1 or Q2, depending upon the ticket T1 or T2 that to linked lists.
is to be purchased. Answer :

2.3 Linked Lists The commonly used terms related to linked lists
are as follows,
2.3.1 Introduction, Concept, Terminology, 1. Header Node
Primitive Operations – Creating, The node that is attached to the first node at the
Inserting, Deleting, Traversing beginning of the linked list is called as Header Node. It
Q42. Define a linked list. List the operations contains some special information related to linked list
possible on a linked list. And also the such as date of creation, number of nodes in the linked
advantages and disadvantages of it. list etc. It can be similar or non similar to the data nodes.
Headernode Datanode Tail
Answer : Model Paper-II, Q16(a) Head
Linked List
Linked list is a linear data structure used to store 2 ID Name 35 64 Null
similar data in memory. The elements in linked list are
not stored in adjacent memory locations but are stored Figure: Header Node in the Linked List
randomly. Linked list is a collection of elements known 2. Data Node
as nodes which contain two fields of information. One Every node in the linked list contains a data
contains the data item and the other contains the link node and the link node. The data node contains the data
or address of the successor element. A node can be members. It will be linked to its predecessor node in the
represented as, list.
Publishers and Distributors Pvt. Ltd. 78
UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
3. Head Pointer
The pointer that points to the node at the beginning of the list is called Head pointer. It can be represented
using a variable. Using this pointer only the further links can also be accessed from the list. The header node might
be dummy node in some cases, so this pointer is called as head pointer and is mostly required.
4. Tail Pointer
As there is a pointer pointing to the head of the list, there is even another pointer that points to the end of
the list (i.e., the last node). This pointer is called as tail pointer.
Q44. Explain about the primitive operations that are performed on the linked lists.
Model Paper-III, Q16
OR
Write an algorithm to delete and insert element in single lined list. May-18, Q6(a) [MGU]
(Refer Only Topics: Insertion, Deletion)
OR
Explain the operations of insertion of a node, deletion of node and traversal in linked list
with examples.
(Refer Only Topics: Insertion, Deletion, Traverse)
Answer : Nov./Dec.-17, Q10(b) [OU]
Operations
The basic operations performed on a singly linked list are insertion, deletion, search and traverse.
1. Insertion
This operation adds a new node to the linked list. This can be done in one of the three ways,
(i) Insertion of node at the beginning of the list.
(ii) Insertion of node at the end of the list.
(iii) Insertion of node at a specified position in the list.
I am a
(i) Insertion of Node at the Beginning of the List Repeated
Question
The steps to insert a node at the beginning of the list is as follows,
(a) Make link field of the new node point to the first node in the list.
(b) This new node becomes the first node.
(c) And later make the header node point to this new node.
Algorithm: Insert_at_beginning
Step 1: Create a new node
Step 2: Move data into new node.
new ← data
Step 3: Make link field point to first node.
new [LINK] → FIRST_NODE.
Step 4: Assign new with first
i.e., new = FIRST_NODE
Step 5: Make the header node point to first node.
HEADER → FIRST_NODE
Step 6: End
Example
Consider an example of inserting the value 15 at the beginning of the list. Initially, the list contains
the following elements.
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL
Figure: Before Insertion
A new node is created at the beginning of the list.

Header New Node 1000 2000 3000
5000 15 1000 3 2000 19 3000 5 NULL
 The value gets inserted at the beginning of the list.
Header New Node 1000 2000 3000
5000 15 1000 3 2000 19 3000 5 NULL
Figure: After Insertion

79 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
(ii) Insertion of the Node at the End of the List
The steps for inserting a new node at the end of the list is as follows,
(a) Traverse the list from first node to last node.
(b) Make the link field containing NULL to point to the address of the new node.
(c) This new node becomes the last node in list. And, the link field stores the NULL value.
Algorithm: Insert_at_end
Step 1: Create a new node
Step 2: Move NULL into the link field of new node.
new[Link]← NULL
Step 3: Move data into the data field of the new node.
new [Data] ← Data
Step 4: Move the contents of HEADER into temp.
temp ← HEADER
Step 5: If temp [link]!= NULL repeat step 6 else go to step 7
Step 6: temp = temp [link]
Step 7: Move the address of the new node into the link field of temp.
temp [link] = new
Step 8: End
Example
Consider an example of inserting value 15 at the end of list. Initially the list contains the following elements,
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL
Figure: Before Insertion
v A new node holding NULL is created at end of the list.
HEADER 1000 2000 3000 new node
1000 3 2000 19 3000 5 4000 Data field NULL
v The value 15 is added at the end of list.
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 4000 15 NULL
Figure: After Insertion
(iii) Insertion of Node at the Specified Location in the List
To insert a node between two nodes for instance between ith node and(i+1)th node,
(a) Link is first traversed up to the ith node.
(b) Then the link field of ith node is made to hold the address of the new node and
(c) The link field of the new node is made to hold the address of the (i+1)th node.
Algorithm: Insert_at_specifiedloc
Step 1: Create a new node
Step 2: Move data into new node.
new ← Data
Step 3: Move the contents of the header into temp.
temp ← HEADER
Step 4: If location = 1 then call insert_at_beginnig
Step 5: If location = n+1 then call insert_at_ending
Step 6: Else, traverse the list from first node to last node. Repeat step 6 until temp = location – 1
temp = temp [link].
Step 7: Move the contents of link field to the link field of new node.
new[link]=temp[link]
Step 8: Move the contents of link field temp to link field of new
new[link]=temp
new ← New
Step 9: End

Publishers and Distributors Pvt. Ltd. 80


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Example
Consider an example of inserting value 15 between 3 and 19. Initially the list contains the following elements.
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL
Figure: Before Insertion
v A new node containing address of next field is created between the 3 and 19.
1000 1500 2000 3000
1000 3 1500 3 2000 19 3000 5 NULL
↑ link field
v Finally, the value 15 is inserted between 3 and 19
1000 1500 2000 3000
1000 3 1500 15 2000 19 3000 5 NULL
Figure: After Insertion
2.Deletion
Deletion of a node from a singly linked list is done possibly in one of the three cases given below,
(i) Deletion of a node from the beginning.
(ii) Deletion of a node from the end.
(iii) Deletion of node from a specified location.
(i) Deletion of a Node from the Beginning
To delete a node from the beginning, the header is made to hold the address the second node. It this
link to the first node is lost then it gets deleted.
Algorithm: delete_at_beginning
Step 1: If HEADER = = NULL then print ‘’list is empty and deletion is not possible’’.
Step 2: Else move the link of second node to HEADER.
HEADER = HEADER → Next
Step 3: End.
Example
HEADER 500 1000 2000 3000
500 15 1000 3 2000 19 3000 5 NULL
Figure: Before Deletion
v Assign header = Next i.e ... Header =1000
v The first node containing value 15 gets deleted from list.
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL

Figure: After Deletion


(ii) Deletion of a Node from the End
To delete a node from the end of the list, traverse the list upto n – 1 node and make the link field of it
to hold NULL.
Algorithm: delete_at_end
Step 1: If HEADER = = NULL then print ‘’ List is empty and deletion is not possible’’.
Step 2: Move the contents of the header to temp.
temp ← HEADER
Step 3: Repeat step 4 untill the last node is reached
temp[link]! = NULL
Step 4: temp ← temp [link]
Step 5: previous [link]←NULL
Step 6: End.

81 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Example
Consider an example of deleting value 15 from the below list:
HEADER 1000 2000 3000 4000
1000 3 2000 19 3000 5 4000 15 NULL
Figure: Before Deletion
HEADER 1000 2000 3000 4000
1000 3 2000 19 3000 5 4000 15 NULL
↑ link field
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL
Figure: After Deletion
(iii) Deletion of Node from a Specified Location
To delete a node from a specified location, for instance an ith node, the list is traversed upto i – 1th
node and then the link field of it is made to hold the address of i + 1th node. With this, the ith node gets
deleted.
Algorithm: delete_at_specified loc
Step 1: If HEADER == NULL then print “deletion is not possible”.
Step 2: Move the contents of the header into temp.
Step 3: If location = =1 then call delete_at_beginning.
Step 4: If location = = n then call delete_at_ending
Step 5: Else traverse the list from first node to last node. Repeat step 6 until temp = location -1
temp = temp[link]
Step 6: Move the contents of the link field of the next node of location.
location-1[link]← location +1[link]
Step 7: End
Example
Now, consider an example to delete item 15 from the given list
HEADER 1000 2000 3000 4000
1000 3 2000 19 3000 5 4000 15 NULL
Figure: Before Deletion
HEADER 1000 1500 2000 3000
1000 3 1500 15 2000 19 3000 5 NULL

↑ link field
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL

Figure: After Deletion
3. Search
To search a particular node, the value of the data field must be matched with the value of data fields of all
the nodes in the list by traversing the list from first to last. This operation is commonly used to insert or delete a
node at specified location.
Example
Consider the below list,
HEADER 1000 2000 3000
1000 3 2000 19 3000 5 NULL

element to be searched.
Figure: Search Operation
To search a node containing 19 in its data field, the data field of all the nodes is matched with 19. If 19 is
found then, the location of that node [i.e,3000] is returned. Else, an error message is returned.

Publishers and Distributors Pvt. Ltd. 82


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Algorithm: Search void slink::create( )
Step 1: Input the DATA to be searched. {
Step 2: Initialize TEMP = HEADER; POS = 1; head=new node;
Step 3: Repeat the steps 4, 5 and 6 untill cout<<“Enter the data for the node:”;
(TEMP! = NULL) cin>>head –> data;
Step 4: If (TEMP → DATA = = DATA) Dis- head–>next=NULL;
play “The data found at POS” an of }
Exit void slink::insert( )
Step 5: TEMP = TEMP → Next {
Step 6: Else, POS = POS + 1 int n;
Step 7: If (TEMP = = NULL) Display “Data char p;
is not found” node*list,*prev,*temp;
Step 8: Exit. list=head;
4. Traverse cout<<“Insert node at front/middle/last? f/m/l:”<<endl;
Traversal is performed on a list by visiting each cin>>p;
node in the list from first node to last node.
if(p==‘f’)
Algorithm: Traverse
{
Step 1: Move the contents of the header
temp=new node;
to temp.
cout<<“Enter the data for the node:”;
temp ← HEADER
cin>>temp–>data;
Step 2: Repeat step 3 until the last node is
reached. temp–>next=head;
temp [link]! = NULL head=temp;
}
Step 3: temp ←temp [link]
if(p==‘m’)
Step 4: End.
{
Q45. Write a C++ Program to implement linked
cout<<“Enter the data for the new node
list.
before:”<<endl;
Answer :
cin>>n;
Program
while(list–>data!=n)
#include<iostream.h>
{
#include<conio.h>
prev=list;
#include<process.h> list=list–>next;
class slink }
{ temp=new node;
private: cout<<“Enter the data for the node:”;
struct node cin>>temp->data;
{ prev–>next=temp;
int data; temp–>next=list;
node*next; }
}*head; if(p==‘l’)
public: {
slink( ) while(list–>next!=NULL)
{ list=list–>next;
head=NULL; temp=new node;
} cout<<“Enter the data for the node:”;
void create( ); cin>>temp–>data;
void insert( ); temp–>next=NULL;
void delnode( ); list–>next=temp;
void display( ); }
}; }

83 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
void slink::delnode() {
{ cout<<list–>data<<“<==>”;
int n,p=0;
list=list–>next;
node *list,*prev,*temp;
}
list=head;
cout<<“Enter the data for the node to be deleted:”; cout<<“NULL”;
cin>>n; }
if(head–>data==n) getch( );
{ }
head=head–>next;
void main( )
p=1;
{
}
else int option;
{ slink s;
while((list–>next!=NULL)&&(list–>data!=n)) while(option!=5)
{
{
prev=list;
clrscr();
list=list–>next;
} cout<<“1.Create( )”<<endl;
if((list–>next!=NULL)&&(list–>data==n)) cout<<“2.Insert( )”<<endl;
{ cout<<“3.Delete( )”<<endl;
temp=list; cout<<“4.Display( )”<<endl;
prev–>next=NULL;
cout<<“5.Exit()”<<endl;
p=1;
cout<<“Enter your option:”;
}
else if(list–>data==n) cin>>option;
{ switch(option)
temp=list; {
prev–>next=list–>next;
case 1:
p=1;
s.create( );
}
delete(temp); break;
} case 2:
if(p==0) s.insert( );
{ break;
cout<<“Node is not present”;
case 3:
}
s.delnode( );
}
void slink::display() break;
{ case 4:
node*list; s.display( );
list=head;
break;
if(list==NULL)
case 5:
cout<<“List is empty”;
else break;
{ }
cout<<“The list is:”; }
while(list!=NULL) }

Publishers and Distributors Pvt. Ltd. 84


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Output Algorithm:Create
Step1: Start
Step2: Create a new node in the memory
new node = (Struct node) sizeof (node)
Step3: Assign the values in new node as follows.
new node → info = x
new node → next = NULL
Step4: Check whether head is NULL or not
if (head = NULL)
{
head = new node
current = new node
}
else
{
current → next = new node
current = current → next
}
Step5: Follow step 1 to 4 to insert remaining element in
the list
Step6: End.
Example
Initially, memory is allocated for the new node.
1000

Figure: Empty Node


Now, the HEADER is made to hold the address
of this node.
Data Link
HEADER field field

1000

A data value 5 is moved into the data field of the


node.
1000

1000 5
Q46. Explain how to create a linked list.
Answer :
The link part of this node is made to hold NULL.
The various steps involved in creating a linked HEADER
list are as follows, 1000 5 NULL
1. Initially, create a new node design.
2. Then, allocate the memory space for new node. Now the contents of HEADER is moved to
3. Create a node containing two parts, namely data temp.
and link. HEADER

(a) The data part holds the data value and 1000 5 NULL
(b) The link part holds the address of the next
node created.
4. Create HEADER to hold the address of the first 1000
node in the list. And NULL to hold the last node. temp

85 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Another new node is created and the address of it is moved to temp1.
HEADER 2000

1000 5 NULL

1000 2000
temp temp

Move the data value 4 to data part and make the link part to hold NULL.
HEADER 1000 2000

1000 5 NULL 4 NULL

1000 2000

temp temp1

To link these two nodes, the link part of temp is made to point to temp1.
HEADER 1000 2000

1000 5 2000 4 NULL

1000 2000

temp

After linking, the contents of temp1 are moved to temp.


HEADER 1000 2000

1000 5 2000 4 NULL

2000
2000
temp
temp1

A linked list with three nodes is created. Repeat the above process until a singly linked list with desired
number of nodes gets created.
2.3.2 Representation of Linked Lists
Q47. Discuss how linked list is represented using array.
Answer : Model Paper-II, Q16(b)

Linked list are allowed to be represented using the arrays. Consider weekdays to be the names of the days
of a week.
Weekdays – {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}
Here weekdays is an order list. All the elements of it are stored in one dimensional array. The linked
organization of it is shown as,
Index Data Link
1. Friday 5
2. Wednesday 7
3. Head Sunday 6
4. Tuesday 2
Saturday –1
5.
Monday 4
6.
7. Thursday 1
Figure: Linked List using Array
In the above figure, data shows the days of a week stored in random locations. This is because the elements
can be stored anywhere in the array. Sequence is maintained by using the link. It depicts the links to the successive
element for every element. The list begins at 3rd location and it is pointed by head.

Publishers and Distributors Pvt. Ltd. 86


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Head = 3
Data[Head] = Sunday
Link[Head] = Link[3]
Data[Link[6]] = Data[4] = Tuesday
In this way, even the other elements can also be represented. By following this all the elements can be
listed in sequential manner.

Figure: Linked Representation


In the above figure head denotes beginning of the list and – 1 denotes end of the list. The link and data are
depicted in two separate arrays in the above figure.
Q48. Explain in brief the concept of linked list using dynamic memory management.
Answer :
The linked list does not need to be stored in adjacent locations. Each element of it can be stored anywhere
in the memory. Every data element is called node which consists of two fields namely data and link. The data field
contains the data member and link field contains the address of the next node in the list. Memory will be allocated
for each newly created node during run time. That is the new node of the list will be created dynamically. The last
node in the list contains 0 (i.e., Null) in order to represent that it is end of the list. Therefore, it can be said that the
linked list maintains data elements in logical order instead of physical order by separating the physical view from
logical view.
Empty Linked List
A linked list is called as empty linked list if it’s head pointer contains NULL value. It is also referred as null
list. Since it does not contain any nodes the length of it will be 0. New nodes can be created and inserted into these
lists. This requires the following things to be considered.
v While writing a program for the list, programmer should not search for specific address except while testing for 0.
v The node locations might change while various runs of the program.
v The nodes might not be stored in sequential locations.
Implementation of a linked list needs the following requirements:
v Mechanism that allocates memory for the node containing one link field atleast.
v Mechanism that verifies for successful allocation.
v Mechanism that releases the allocated memory for a node and adds it to free pool of memory when required.
In C++, dynamic memory management functions are used to perform the above tasks. The operators called
new and delete are used to verify whether the memory allocation is successful or not.

2.3.3 Linked List Abstract Data Type


Q49. Explain the concept of linked list ADT and data structure of a node.
Answer : Model Paper-III, Q15(a)

Linked List Abstract Data Type


The implementation of a linked list using the pointers is the most efficient and flexible way. Every node in
linked list consists of two fields namely a data field (which stores the data) and a link field (which holds the address
of the next node). The Abstract representation of a linked list is as follows,
ld ld
a fie k fie
t n
Da Li

2 3 4 Null

87 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Every linked list maintains as external link called Data Structure of a Node
Head which points to the first node of the linked list. The A node consists of two fields they are data field and
representation of a linked list using Head is as follows. link field. Data field is used to store the given data and the
Head link field is used to hold the address of its next node. The
node pointer which points to another node is also of same
2 3 4 Null type as itself. Generally, a node is a group of two different
types of data which are together logically grouped through
The abstract representation of a linked list in C++ data type object. It is also called as ‘self-referential object’.
can be done by considering it as object of class Linked The data structure of a Node can be represented as follows,
list.
class Node
class Linkedlist {
{ public
private: int val;
Node * link; //Node is data type,
Node * Head; //data member
//link is the pointer
public: //of data type node
Linked list( ); //constructor };
~Linked list( ): //destructor class List
{
//Statements
private:
}; Node * Head;
The class consists of only one data member that public:
is a pointer that points to the starting node of the list. The //methods( );
member functions along with constructor and destructor };
will process the list and the Head is used to access the list. A simple code snippet to illustrate a linked list
The member functions are public and Head is private. It node structure is as follows,
is declared as private to avoid the list to be accessed by class Node
outside objects. A program to illustrate the linked list is {
as follows,
public:
/*Linked list program*/ Node * link;
class linkedlist int val;
{ }*frst, v;
private: frst = & v;
v.val = 5;
Node * Head:
v.link = Null;
Node *Tail;
The below statement will print 5;
int n;
cout << frst –> val; //output statement
public: Q50. Discuss the operations performed on List
Linkedlist ( ) ADT.
{ Answer :
Head = Tail = Null; The various operations performed on List ADT
are as follow,
n = 0;
1. Insertion of a Node
} Inserting a node into the list can be done at the
void create( ); beginning, at the end or at the middle depending upon
void Append(int d); the user requirement.
(a) Insertion of Node at Middle Position
void Insert(int d, pos);
Let ‘Newnode’ be the node inserted in the middle
void Delete(int pos); of the list. Assume that previous node be the node
void Traverse( ); after which new node must be inserted. Therefore, the
void Reverse( ); new node becomes the successor of the previous and
predecessor for the next data. Insertion of new node at
}; the middle is illustrated as follows,

Publishers and Distributors Pvt. Ltd. 88


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Head
A B C Null

D
Previous
Newnode
1. Previous –> link holds the pointer, to its successor. Set the link of pointer as the link of newnode.
Newnode –> link = previous –> link
The newnode becomes the predecessor of the successor of the previous.
Previous

Head
A B C Null

D
Newnode
Figure: Link Manipulation for Insertion
2. Now set the address of new node as the link of previous node to make the Newnode as the successor for the
previous node i.e.,
Previous –> link = Newnode
Head
A B C Null

D
Newnode
Figure: Link Manipulation for Insertion
(b) Insertion of Node at First Position
Inserting a node at first position of the list needs two steps to be performed. Make the link of newnode to
hold the contents of head because head will point to the beginning of the list.
1. New node –> Linked = Head
Head
A B C

D
Newnode
2. Set Head to point to the Newnode
Head = Newnode
A B C
Head
D C Null
Newnode Newnode
(c) Insertion of Node at the End
The insertion of a node at end involves in two steps.
Head
A B C Null

Newnode D

1. Move the link of previous node i.e., the last node into the link field of new node.
Newnode –> link = Previous Node –> link
Since previous node –> link = Null then Newnode –> link = Null
A B C Null
Head
D Null
Newnode

89 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
2. Make the newnode as the successor of the last element.
Previous Node –> link = Newnode
Head
A B C

D Null
Newnode

With this, the new node becomes the last node of the list.
2. Deletion of a Node
Deletion of a node from the list needs link manipulation. To delete a node, the link between the node to be
deleted, its predecessor and successor should be modified.
Prev Pr

Head
A B C D E N

Figure: Link Manipulation Process to Delete a Node


Algorithm to delete a node from the list is as follows,
Step 1: Let pr be the node to be deleted and prev be the predecessor of pr.
Step 2: Set both pr and prev to Head.
Step 3: Search for the node to be deleted by traversing the list.
Step 4: Make the Link of prev to point to the successor of pr.
Prev –> Link = Pr –> Link
Step 5: Free the memory of pr
delete pr;
Step 6: Stop.
The node to be deleted can be at any position i.e., at first, middle or last depending upon the user requirement.
(a) Deleting the First Node
Deletion of first node needs the head to be manipulated. This is because it is the head that points to the first
node in the list.
1. Set a pr to the first node before manipulating the Head link. Make head to point second node, then the second
node becomes the first node.
pr = Head;
Head = Head –> Link
Head
A B C D N

Pr
Figure: Link Manipulation
2. Free the memory of first node and delete pr;
After these two steps the Head pointer points to the second node and the memory allocated for the first node
is cleared. The second node now becomes the first node.
(b) Delete a Node from any Position
The process of deleting a Node from any position is also suitable to delete the last node. This can be done
with the following statements.
1. Let prev be the previous node and pr be the node to be deleted.
2. Set the link of pr to the link of prev.
prev –> link = pr –> link
3. Free the memory of the deleted node i.e., memory of pr.
delete pr;

Publishers and Distributors Pvt. Ltd. 90


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
3. Linked List Traversal Example to illustrate the function is as follows,
Traversal is a method of processing the data Let the list L1 = {1, 2, 3}
elements sequentially which involves in searching, 1. Let pr be the pointer pointing to Head initially
sorting, retrieving etc. Traversing begins from the Head, pr = Head;
the first node is accessed and through the Head node link
1 2 3 Null
and the second node is accessed through the first node Head
link. In this way all the elements can be accessed.
2.Traversing begins from the first node until the
Algorithm last node is reached. Let pr be the pointer.
Step1: Let the first node in the list i.e., Head to be pointed pr = Head
Head
by pr. 1 2 3 Null
pr = Head
Pr
Step2: If pr = Head = = Null go to step 6
3. The required processing is done on node pointed
Step3: Process the data field by performing the specified by pr and control is moved to next node.
operations such as printing, searching etc. Head
1 2 3 Null
Step4: Move pr to next node
Present = Present –> Link Pr

Step5: Go to step 2 4. The above process is continued until the last node
is reached.
Step6: Stop Head
1 2 3 Null
The traversal can be done in two ways.
Pr
(a) Non-recursive method
5. When pr = = Null then traversing stops.
(b) Recursive method. Head
1 2 3 Null
(a) Non-Recursive Method
The output of the above example would be
In Non - recursive method the function doesn’t
call itself. A code to illustrate the non - recursive 1
method is as follows. 12
void linkedlist :: Traverse( ) 123
(b) Recursive Traversal Method
{
In Recursive traversal method, the function
Node *t = Head; calls itself. The code to illustrate the recursive traversal
if( t = = Null) method is as follows,
void linkedlist
cout << “List is empty\n”;
{
else
private :
{ Node * Head, * T;
while(t! = Null) void rec_traversal (Node * t)
{ {
if (t = = Null)
cout<< t –> data << “\t”;
return;
t = t –> link; cout << t –> val <<“\t”;
} Rec_traversal (t –>link);
} }
cout << “\n”; public :
void Create( );
}
void Display( );
The above defined function will be accessible void r_traversal( )
to all the functions. It can be used to perform the
{
operations like search, update and print etc., with slight
modifications. A node here can hold multiple data rec_traversal (Head);
elements. cout <<“\n”;

91 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
} Q52. Write a program to create Doubly linked
}; list. (May/June-19, Q6(b) [MGU] |

void main( ) Nov./Dec.-18, Q6(b) [MGU])

{ OR
linkedlist L; Write a program to create a double linked
list insert, delete and search for an
L.Create( );
element operations.
L.r_traversal( );
Answer : Nov./Dec.-19, Q6(b) [OU]
}
Program
The output of the above code for the list
#include <iostream>
L = {1, 2, 3} would be 1 2 3
#include <stdlib.h>
2.3.4 Linked List Variants – Singly using namespace std;
Linked List, Doubly Linked List, struct node
Linear and Circular Linked List {
struct node *prev;
Q51. Discuss in brief about singly linked list
int n;
and doubly linked list.
struct node *next;
Answer : (Model Paper-III, Q15(b) | Nov./Dec.-19, Q8(b) [MGU])
}*h,*temp,*temp1,*temp2,*temp4;
Singly Linked List void insert();
A list in which each node is linked to another void insert_pos();
node is called single linked list. Every node consists of void display();
two fields namely, the data field and link field. The data void sort();
field holds the data the link field holds the address of the void search();
next node. This is shown in figure below,
void delete_pos();
int count = 0;
Hey!
NODE Don’t
int main()
escape {
Figure: Node of a Singly Linked List from
int ch;
me
Example h = NULL;
temp = temp1 = NULL;
cout<<“1.Insert 2.Insert at position 3.Delete
Figure: Singly Linked List 4.Search 5.Sort 6.Display 7.Exit\n”;
while (1)
The address of each node is stored in the link
{
field of previous node. And, the address of the first
node is stored in the Header node. The link field of the cout<<“\nEnter choice :”;
last node contains NULL value. cin>>ch;
switch (ch)
Doubly Linked List
{
In a doubly linked list, every list of element has
case 1:
both a reference to the next element and a reference
insert();
to the previous element. Hence, doubly linked list can
traverse in both directions and make use of two point- break;
ers. Diagrammatically, a node can be represented as, case 2:
LLINK Info RLINK
insert_pos();
break;
Figure: Node case 3:
L R
delete_pos();
break;
NULL 10 20 30 NULL case 4:
Figure: Doubly Linked List search();
RLINK contains the address of succeeding node break;
and LLink contains the address of predecessor node. case 5:
The LLink of the first node and RLINK of the last node sort();
holds NULL. The Info fields contains the actual data. break;

Publishers and Distributors Pvt. Ltd. 92


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
case 6: if ((h == NULL) && (pos == 1))
display(); {
break; create();
case 7: h = temp;
exit(0); temp1 = h;
default: return;
cout<<“\n Wrong choice”; }
} else
} {
return 0; while (i < pos)
} {
void create() temp2 = temp2->next;
{ i++;
int data; }
temp =(struct node *)malloc(1*sizeof create();
(struct node)); temp->prev = temp2;
temp->prev = NULL; temp->next = temp2->next;
temp->next = NULL; temp2->next->prev = temp;
cout<<“Enter value to node :”; temp2->next = temp;
}
cin>>data;
}
temp->n = data;
void delete_pos()
count++;
{
}
int i = 1, pos;
void insert()
cout<< “Enter position of element to be deleted :”;
{
cin>>pos;
if (h == NULL)
temp2 = h;
{ if ((pos < 1) || (pos >= count + 1))
create(); {
h = temp; cout<<“Position out of range to delete”;
temp1 = h; return;
} }
else if (h == NULL)
{ {
create(); cout<<“Empty list”;
temp->next = h; return;
h->prev = temp; }
h = temp; else
} {
} while (i < pos)
void insert_pos() {
{ temp2 = temp2->next;
int pos, i = 2; i++;
cout<<“Enter position of element to be inserted : ”; }
cin>>pos; if (i == 1)
temp2 = h; {
if ((pos < 1) || (pos >= count + 1)) if (temp2->next == NULL)
{ {
cout<<“Position out of range to insert”; cout<<“Node deleted from list”;
return; free(temp2);
} temp2 = h = NULL;
if ((h == NULL) && (pos != 1)) return;
{ }
cout<< “Empty list cannot insert other than }
1st position”; if (temp2->next == NULL)
return; {
} temp2->prev->next = NULL;

93 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
free(temp2); count++;
cout<<“Node deleted from list”; }
return; cout<<“Element”<<data<< “not found in list\n”;
} }
temp2->next->prev = temp2->prev; void sort()
if (i != 1) {
temp2->prev->next = temp2->next; int i, j, x;
if (i == 1) temp2 = h;
h = temp2->next; temp4 = h;
cout<<“Node deleted”;
if (temp2 == NULL)
free(temp2);
{
}
cout<< “List empty to sort”;
count--;
} return;
void display() }
{ for (temp2 = h; temp2 != NULL; temp2 =
temp2 = h; temp2->next)
if (temp2 == NULL) {
{ for(temp4 = temp2->next; temp4 != NULL;
cout<<“Empty list \n”; temp4 = temp4->next)
return; {
} if (temp2->n > temp4->n)
cout<<“Linked list elements from begining :”; {
while (temp2->next != NULL) x = temp2->n;
{
temp2->n = temp4->n;
cout<<temp2->n<< “ ”;
temp4->n = x;
temp2 = temp2->next;
}
}
cout<<temp2->n<< “ ”; }
} }
void search() display();
{ }
int data, count = 0; Output
temp2 = h;
if (temp2 == NULL)
{
cout<< “Empty list \n”;
return;
}
cout<< “Enter value to search :”;
cin>>data;
while (temp2 != NULL)
{
if (temp2->n == data)
{
cout<<“Data found in”<<count +
1<<“position”;
return;
}
else
temp2 = temp2->next;

Publishers and Distributors Pvt. Ltd. 94


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Q53. Write a short notes on following, Consider ‘A’ as circular linked list.
(i) Circular linked list (i) Inserting an Element N to the Left End of the List
(ii) Linear linked list. Step 1 : Call GETNODE(x), //Create a node x
Answer :
(i) Circular Linked List
In a linked list, if data item needs to added, then
the entire list has to be searched from the beginning of the Step 2 : INFO(x) = N; //Insert ‘N’ as Info in Node x
node because the last node is a null pointer. Therefore, it is
not possible to access any arbitrary item in a linked list. To
overcome this issue, circular linked lists are created. This
list can be used to add data items (info) without starting
from the beginning irrespective of the location. Step 3 : LINK(X) = LINK(A); //Assign the link of
A circular linked list is created by making the //‘A’ with N address
“link” field of the last node point to the first node in //of node x
the list. In circular linked list, there is no NULL link to
indicate the end of the list. For this purpose, it uses a
pointer called the head that stores the address of the first
node. The head is used to stop iterating through the list
after traversing the list once.
Head
Step 4 : LINK(A) = X;
Info Info Info

Figure: Circular Linked List


(ii) Linear Linked List
List is said to be linear if it contains elements in
sequential order. The elements in the linear list can have
either zero or one successor that is, they can have only (ii) Inserting an Element N towards the Right End
one link or atleast one successor. That the insertion and of the List
deletion operations can be easily performed on linked Step 1 : Call GETNODE(x);
lists since there is no need to shift other elements of the //Create a new node Node x
list for inserting or deleting a new or an existing element
respectively. A binary search cannot be performed on the
linked lists. Only a sequential search can be performed.
Example Step 2 : INFO(x) = N; //Insert Info N in Node x
Link Link

Data Data Data


Linear list
Step 3 : LINK(x) = LINK(A);
Null Pointer
//Set LINK(A) as LINK(x)
Figure: Linear Linked List
In the above figure all the elements have only one
successor except the last element. The link field of the
last element has a null pointer. Therefore, the last element
indicates the end of the list. Linear lists are also called
as non linear lists.
Q54. Explain the operations of inserting a node,
deleting a node and traversal in a circular Step 4 : LINK(A)=x; //LINK(A) is assigned to
linked list with examples. Don’t Think //node x
I am Complex
Answer : Nov./Dec.-18, Q10(b) [OU]
Operations on Circularly Linked
List
Operations on circular linked
list are illustrated below with an example.

95 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Step 5 : A = x; //Set Node x as A Step3: temp = temp → next
Assign next address to temp.
temp

Head
5 10 15

(iii) To Delete the Left Most Node from the List A,


Set Temp to the Left Most Node Step4: Repeat step 2, step 3 until
Step 1 : P = LINK(A); //Assign the address of node temp! = First i.e., print the data in the nodes
‘A’ to pointer P until temp reaches the first node.
A
P
2.3.5 Representation Stacks and
Queues Using Singly Linked Lists
Q55. Explain the representation of stack using
a linked list.
Step 2 : Temp = INFO(P); //Store the Info which Answer : Nov./Dec.-18, Q10(a) [OU]
//is referred by the pointer Stack using Linked List (Dynamic Implementation)
//P in variable Temp
Stack is implemented using linked list so as to
P A
overcome the problem encountered while implementing
it using arrays. Here, the nodes are inserted or deleted
from only one end of the linked list. Stack represents a
singly connected list when it is implemented using linked
Temp=INFO (P) list, that consist of nodes. Every individual node contains
Step 3 : LINK(A) = LINK(P); //Set Link(A) as a data and a pointer that gives the address location of
//LINK(P); next node present in the list. The node in the linked list
P A is a structure which is in the following form,
struct node
{
LINK(A)=LINK(P) int data;
node *link;
Step 4 : Call RETURN (P)
};
In the above code, link is a
pointer that points to the address of
next node. Initially, the pointer always points to the top
element of the stack. When push operation is executed,
P
Return the node a new node is created which becomes the top node of
pointed by P the stack. The pointer field of this node points to the next
(i.e., previously created) node. This implementation is
(iv) Traversal in a Circular Linked List efficient since the program informs the compiler about
The traversal in a circular linked list starts with the the memory requirement during the execution time.
head node and it continues until the first node is reached The two operations which can be performed on
again. stacks using linked lists are,
Step1: First! =NULL (i) Push stack operation
Initially, check whether the list is not equal to (ii) Pop stack operation.
Null (i.e., list is not empty) (i) Push Stack Operation
Step2: temp → data Push stack operation is an insertion operation in
Next, print the data of the current node. which an element inserted onto a stack. The insertion is
temp
done in the following way,
(a) Initially, check whether there is enough space
Head in the memory for inserting the new node, then
5 10 15 memory for the new node is allocated from
dynamic memory. The newly allocated node now
becomes new stack top.

Publishers and Distributors Pvt. Ltd. 96


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
(b) As soon as memory is allocated to new Example
node, the data is assigned to stack node and
then link field of this node points to the next
node, which was previously the stack’s top
node.
(c) Stack top pointer value is updated and value
of the count field is incremented by 1.
Example

Figure (3): Stack After Pop Operation


Q56. Write a C++ program to implement stack
using singly linked list.
Answer :
Program
Figure (1): Stack Before Invoking Push, Pop #include <iostream>
#include<stdlib.h>
using namespace std;
struct Stack_Node
{
int data;
struct Stack_Node *link;
};
struct Stack_Node* top = NULL;
void push(int item)
{
struct Stack_Node* newStack_Node = (struct Stack_
Node*) malloc(sizeof(struct Stack_Node));
newStack_Node->data = item;
newStack_Node->link = top;
top = newStack_Node;
Figure (2): Stack After Push Operation }
(ii) Pop Stack Operation void pop()
The deletion operation in a stack is referred as pop {
stack operation. In pop operation, the data present in the if(top==NULL)
top node of a stack is sent to the calling algorithm (i.e., cout<< “Stack Underflow”<<endl;
the data part is deleted from the node). After sending the else {
data, the node is logically deleted only after adjusting the cout<< “The element deleted from the stack is:”<<
pointer. Now, the pointer points to the next node of the top->data <<endl;
deleted node. As soon as the node is deleted logically, the top = top->link;
physical deletion of the node takes place. The physical }
deletion of node is done by recycling the memory and then
}
the stack’s count field is decremented by 1. However, the
algorithm returns any of the following status. void display()
If the pop operation is successful, then true value {
is returned or else false value is returned if elements are struct Stack_Node* ptr;
popped from an empty stack. if(top==NULL)

97 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
cout<< “stack is empty”; Output
else {
ptr = top;
cout<<“The items/elements in the stack are:”;
while (ptr != NULL)
{
cout<< ptr->data << “ ”;
ptr = ptr->link;
}
}
cout<<endl;
}
int main() {
int op, item;
cout<<“1) Push()”<<endl;
cout<<“2) Pop()”<<endl;
cout<<“3) Display()”<<endl;
cout<<“4) Exit”<<endl;
do { Q57. Explain the representation of queue using
cout<<“Enter the choice:”<<endl; a linked list.
cin>>op; Answer : June/July-19, Q10(b) [OU]
switch(op) Queue using Linked Lists
{ Apart from representing
case 1: queue using array, linked list can also
{ be used for implementing queues
cout<<“Enter item to be pushed/inserted into (FIFO) data structure. Since, the list
the stack:”<<endl; does not impose any sort of storage I am tou
gh but important
cin>>item; restrictions (i.e., they can hold any
push(item); number of elements). The allocation of elements is done
break; dynamically, due to which the size of linked list can grow till
} there is enough memory available for dynamic allocation. The
case 2: main advantage of representing a queue using linked list is that,
{ it allows the user to select any end of the list to either insert or
pop(); delete data items. It is very much easier to delete the first node
than the last node since for deleting last node, it is necessary
break;
to locate previous node, which consumes more time.
}
case 3: Now, consider the following list that consists of
three data items,
{
display();
break;
}
case 4: After insertion of ‘4’,
{
cout<<“Exit”<<endl;
break;
} New items will be added at the rear end of the list.
default: After deletion
{
cout<<“Invalid Choice”<<endl;
}
}
}while(op!=4);
return 0;
} Items are deleted from the front end of the list.

Publishers and Distributors Pvt. Ltd. 98


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III
Program else
#include <iostream> {
#include<stdlib.h> cout<< “Element deleted from queue is :”
using namespace std; <<front->data<<endl;
struct Queue_Node free(front);
{ front = NULL;
int data; rear = NULL;
struct Queue_Node *pointer; }
}; }
struct Queue_Node* front = NULL; void Display()
struct Queue_Node* rear = NULL; {
struct Queue_Node* temp; temp = front;
void Insertion() if ((front == NULL) && (rear == NULL))
{ {
int item; cout<< “Queue is empty”<<endl;
cout<< “Insert the element in queue :”<<endl; return;
cin>>item; }
if (rear == NULL) cout<< “Queue elements are:”;
{ while (temp != NULL)
rear = (struct Queue_Node *)malloc(sizeof {
(struct Queue_Node)); cout<<temp->data<< “ ”;
rear->pointer = NULL; temp = temp->pointer;
rear->data = item; }
front = rear; cout<<endl;
} else }
{ int main()
temp=(struct Queue_Node *)malloc(sizeof {
(struct Queue_Node)); int op;
rear->pointer = temp; cout<< “1) Insertion()”<<endl;
temp->data = item; cout<< “2) Deletion()”<<endl;
temp->pointer = NULL; cout<< “3) Display()”<<endl;
rear = temp; cout<< “4) Exit”<<endl;
} do
} {
void Deletion() cout<<“Enter the choice :”<<endl;
{ cin>>op;
temp = front; switch (op)
if (front == NULL) {
{ case 1: Insertion();
cout<< “Underflow”<<endl; break;
return; case 2: Deletion();
} break;
else case 3: Display();
if (temp->pointer != NULL) break;
{ case 4: cout<< “Exit”<<endl;
temp = temp->pointer; break;
cout<< “Element deleted from queue is :” default: cout<< “Invalid choice”<<endl;
<<front->data<<endl; }
free(front); } while(op!=4);
front = temp; return 0;
} }

99 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Output

2.3.6 Application of Linked List – Garbage Collection

Q58. Explain how Garbage collection acts as an application of linked list.


Answer :
Large number of free memory blocks will be available after the memory allocations and deallocations.
These blocks are linked to each other by using the pointers in order to reuse them. The Head pointer is connected
to the first free memory block in the list. When a free memory block is required, the memory allocator will search
for the suitable block and deletes it from the list.
Memory management module is one of the components of an operating system that contains a list of unused
memory cells. Generally, the list needs certain operations to be performed on it like searching, sorting, inserting,
etc. This type of list is also called list of available space or free storage list or free pool. All the memory blocks
free by a program (after deallocation process) will be stored in the free pool for further usage. Garbage collection
is the process of collecting the free memory and inserting them into the free pool. It has two phase process given
as follows,
1. Initially, it runs through all the list and tags the lists that are being used currently.
2. Next it runs through the memory blocks by collecting, inserting the unused blocks into the free pool.
This process occurs in the case of overflow, underflow and when the CPU is idle. Overflow is the process
that occurs when a node is to be inserted, but no space available in the data structure. Underflow is the process that
occurs when a node is to be deleted from the empty list.
Circularly, double linked list is the most preferable data structure for garbage collection. It allows the user
to traverse the list infinitely. Since it is circular and allows to traverse from both the ends.

Publishers and Distributors Pvt. Ltd. 100


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III

EXERCIsE AND PRACTICE QUEsTIoNs

Short Questions

1. Explain Recursion with example. (Refer Q1) May/June-19, Q2 [MGU]

2. What are the advantages of recursion? (Refer Q2) Nov./Dec.-19, Q3 [MGU]

3. Write a recursive algorithm to find XY. (Refer Q3) June/July-19, Q4 OU]

4. What are the demerits or recursion? (Refer Q4) Nov./Dec.-18, Q4 [OU]

5. Differentiate between iteration and recursion approaches in


problem solving. (Refer Q5) Nov./Dec.-17, Q3 [OU]

6. What is the purpose of a stack in implementing a recursive


procedure? (Refer Q6) Nov./Dec.-17, Q2 [MGU]

OR
Explain the use of Stack to find the factorial of a number
using recursion. (Refer Q6) Nov./Dec.-18, Q3 [OU]

7. Describe execution of recursive calls with example. (Refer Q7) Nov./Dec.-19, Q4 [OU]

8. Define circular queue. (Refer Q10) Nov./Dec.-19, Q4 [MGU]

9. Write a short notes on double-ended queue (DEQUE). (Refer Q11) Nov./Dec.-17, Q4 [OU]

10. Write a short notes on applications of queues. (Refer Q12) May/June-18, Q3 [OU]

11. What are the advantages of circularly list over single linked
list? (Refer Q17) May-18, Q2 [MGU]

12. Explain the insertion of a node in singly linked lists with


examples. (Refer Q18) May/June-18, Q4 [OU]

13. Why linked list is called dynamic data structure? What are the
advantages of using linked list over arrays? (Refer Q19) Nov./Dec.-19, Q3 [OU]

14. What is Garbage Collection? (Refer Q20) Nov./Dec.-18, Q2 [MGU]

Essay Questions

15. What is recursion and write an example for recursion? (Refer Q21) Nov./Dec.-19, Q10(a)(i) [OU]

16. What is meant by Recursion? Write a recursive algorithm to


generate Fibonacci sequence? (Refer Q22) Nov./Dec.-17, Q6(a) [MGU]

17. Briefly describe about the direct recursion, indirect recursion


and tree recursion with examples. (Refer Q25) May/June-18, Q10(a) [OU]

18. Explain Tower of Hanoi using recursion. Write the algorithm and
draw the tree representation of recursive calls of the algorithm
for 3 disks. (Refer Q28) June/July-19, Q10(a) [OU]

19. What is queue? Explain primitive operations on queue. (Refer Q31) Nov./Dec.-17, Q10(a) [OU]

20. What is a queue? Give the ADT for a queue. (Refer Q33) May/June-18, Q10(b) [OU]

101 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

21. Write a C++ program to implement queue ADT. (Refer Q35) Nov./Dec.-19, Q8(a) [MGU]

22. Explain the operations of Queues using Arrays. (Refer Q36) May/June-19, Q6(a) [MGU]

23. Discuss on Circular Queue with examples. (Refer Q37) Nov./Dec.-18, Q6(a) [MGU]

OR
Explain implementation of circular queue using arrays. (Refer Q37) May/June-18, Q10(b)(ii) [OU]

24. Write short note on:


(i) Recursion
(ii) Double-ended queues. (Refer Q39) May-18, Q6(b) [MGU]

25. What is queue? And explain about circular queue and double
ended queue. (Refer Q40) Nov./Dec.-19, Q10(a)(ii) [OU]

26. Write an algorithm to delete and insert element in single lined


list. (Refer Q44) May-18, Q6(a) [MGU]

OR
Explain the operations of insertion of a node, deletion of node and
traversal in linked list with examples. (Refer Q44) Nov./Dec.-17, Q10(b) [OU]

27. Discuss in brief about singly linked list and doubly linked list. (Refer Q51)
Nov./Dec.-19, Q8(b) [MGU]

28. Write a program to create Doubly linked list. (Refer Q52)


(May/June-19, Q6(b) [MGU] | Nov./Dec.-18, Q6(b) [MGU])

OR
Write a program to create a double linked list insert, delete and
search for an element operations. (Refer Q52) Nov./Dec.-19, Q6(b) [OU]

29. Explain the operations of inserting a node, deleting a node and


traversal in a circular linked list with examples. (Refer Q54) Nov./Dec.-18, Q10(b) [OU]

30. Explain the representation of stack using a linked list. (Refer Q55) Nov./Dec.-18, Q10(a) [OU]

31. Explain the representation of queue using a linked list. (Refer Q57) June/July-19, Q10(b) [OU]

Publishers and Distributors Pvt. Ltd. 102


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III

INTERNAL AssEssMENT/EXAM

I Multiple Choice
1. Linked lists are best suited for ______. [ ]
(a) Relatively permanent collections of data

(b) The size of the structure and the data in the structure are constantly changing

(c) Both (a) and (b)

(d) None of the above

2. Application(s) of a singly list ______. [ ]

(a) Representation of polynomial expressions

(b) Representation of sparse matrix

(c) Both (a) and (b)

(d) None of the above

3. In this list, for any node N, N → rlink → llink is the address of the node N itself. [ ]

(a) Singly linked list

(b) Doubly linked list

(c) Circular linked list

(d) None of the above

4. The drawback of linked lists ______. [ ]

(a) More memory space

(b) No random access

(c) More programming effort

(d) All the above

5. A _____ list allows traversal of the list in forward direction, but not in backward direction. [ ]

(a) Singly linked list

(b) Doubly linked list

(c) Circular linked list

(d) Both (a) and (b)

6. A doubly linked list is a data structure having an ordered list of nodes, in which each node consist of
______ pointers. [ ]

(a) 3

(b) 2

(c) 1

(d) 0

103 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
7. Common operations of linked list are insertion, deletion, retrieval ______. [ ]
(a) Only insertion
(b) Deletion
(c) Traversal
(d) None of the above
8. Recursive function is of ___________ when compared to its equivalent code. [ ]
(a) Short length
(b) Simpler
(c) Highly reliable
(d) All the above
9. _____ statements are executed repeatedly until a condition is satisfied. [ ]
(a) Recursion
(b) Iteration
(c) Function call
(d) None of the above
10. A queue structure in which elements can be inserted or deleted from either ends of the queue is called
as __________. [ ]
(a) Deque
(b) Circular queue
(c) Priority queue
(d) None of the above

II Fill in the Blanks


1. _____ is a function which calls itself.

2 Iteration statements include _____, _____ and _____ loops

3. Types of linked list are _____, _____ and _____ linked lists

4. In _____ list, the last node link points to the first node of the list.

5. A situation when a linked list START = NULL is _____.

6. A queue structure in which elements are inserted or deleted from queue based on priority is known as
_____.

7. In _____, every node has both a reference to the next element and a reference to the previous element.

8. _____ is only performed during program execution.

9. Traversing of the list is faster if the linked list is _____.

10. Queue is also known as _____.

Publishers and Distributors Pvt. Ltd. 104


UNIT-2: Recursion, Queues and Linked Lists Computer Science Paper-III

KEY
I. Multiple Choice

1. (b) 2. (c) 3. (b) 4. (d) 5. (a)

6. (b) 7. (c) 8. (d) 9. (b) 10. (a)

II. Fill in the Blanks

1. Recursive function

2. for, while, do-while

3. Singly, doubly, circular

4. Circular linked

5. Underflow

6. Priority queue

7. Doubly linked list

8. Garbage collection

9. Singly linked list

10. FIFO (First-in-first-out)

105 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

III Very Short Questions and Answers

Q1. What is recursion?


Answer :
Recursion is the process or technique by which a function calls itself. This function is called recursive
function.
Q2. What is Queue?
Answer :
A queue is an ordered collection of items in which new items may be inserted at one end known as rear and
existing items may be deleted from other end known as front end.
Q3. Define a linked list.
Answer :
Linked list is a linear data structure used to store similar data in memory. The elements in linked list are not
stored in adjacent memory locations but are stored randomly.
Q4. Define circular queue.
Answer :
Circular queue is similar to ordinary queue, but the major difference is that in former the rear pointer can
point to the front element.
Q5. Define queue ADT.
Answer :
The queue abstract data type consists of data type definitions and queue operations. The queue ADT type
definitions define two structures, namely node structure and head structure.

Publishers and Distributors Pvt. Ltd. 106


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III

UNIT
3 Trees, Graphs and Hashing

SYLLABUs
Trees: Introduction, Representation of a General Tree, Binary Tree Introduction, Binary Tree
Abstract Data Type, Implementation of Binary Trees, Binary Tree Traversals – Preorder, Inorder,
Postorder Traversals, Applications of Binary Trees Briefly.

Graphs: Introduction, Graph Abstract Data Type, Representation of Graphs, Graph Traversal –
Depth-first Search, Breadth-first Search, Spanning Tree – Prim’s Algorithm, Kruskal’s Algorithm.

Hashing: Introduction, Hash Functions, Collision Resolution Strategies.

LEARNING OBJECTIVEs
 Tree and its Terminology.
 Binary Tree ADT and its Implementation.
 Various Tree Traversal Techniques – Preorder, Inorder, Postorder.
 Graphs and its Representation.
 Spanning Tree Algorithm i.e., Prim’s and Kruskal’s Algorithms.
 Hashing, Hash Functions and Collision Resolution Strategies.

INTRoDUCTIoN
Tree is a non-linear data structure represented in a hierarchical manner. There are
various approaches of representing a tree i.e., linear list or linked list. A tree can be
said to be a binary tree, if it contains atmost two childs for each node. It is possible to
perform different operations such as insert, delete, create and display on a binary tree.
The different tree traversal operations include in-order, pre-order, post-order each of
which has their own method of traversing a tree.

A Graph is defined as G = (V, E). Here, V represents the set of elements called nodes and
E represent the set of edges of the graph identified with a unique pair (U, V) of nodes.

Hash table is a data structure of fixed size that is used to store the dictionary pairs. Hashing
is a technique that makes use of a hash function for mapping pairs to the corresponding
(entries) position in a hash table. For instance, Browser programs use hashing for caching
the web pages.

107 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

P a r t- A S h o rt Q u e s t i o n s a n d A n s w e r s

Q1. Define the terms: tree, complete binary tree.


Answer : Model Paper-III, Q7

Tree
A tree is a non-linear data structure that can be represented in a hierarchical manner. It contains a finite set
of elements called ‘nodes’ which are connected to each other using a finite set of directed lines called ‘branches’.
Example
A

B C

D E F G

Complete Binary Tree


A variation of full binary tree is complete binary tree in which if a binary tree has depth d then,
1. Any node n at level less than (d – 1) has two childs.
2. For any node n in the tree with right descendant at level d, n must have a left child. Moreover, every left
descendant of node n is either a level at leaf d or has two childs.
Q2. Define,
(i) Spanning tree
(ii) Binary tree.

Answer : (Model Paper-I, Q7 | May-18, Q3 [MGU])

(i) Spanning Tree I am Simple and Easy

A spanning tree for a connected, undirected graph, G = (V, E), is a subgraph of G that is an undirected tree
and contains all the vertices of G. It can also be defined as “A sub graph T = (V, E) is a spanning tree of G if T is a
tree. A spanning tree of a graph should include all the vertices and a subset of edges (E)”.
(ii) Binary Tree
A binary tree ‘T’ is defined by finite set of elements called nodes such that,
(a) A binary tree is empty or
(b) It consists of a node called ‘root’ which includes two binary trees called left subtree and right subtree of
the root.
Below figure represents a binary tree,
A Root

B C
Right subtree of A
Left subtree of A

D E F

A binary tree (a)

Figure: Binary Tree


The nodes of the given binary tree are A, B, C, D, E, F.

Publishers and Distributors Pvt. Ltd. 108


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Q3. List the operations that can be performed Q5. What are the applications of trees?d Simple
t an
on a binary tree. Shor
Answer : June/July-19, Q5 [OU]
Answer : Model Paper-II, Q7
Some of the applications of trees are,
The operations that can be performed on a
binary tree are, 1. Manipulation of arithmetic
expression
1. Insertion
2. Constructing symbol table.
This operation adds a node to the current
binary tree. 3. Maintaining symbol table.
2. Deletion Q6. Define the terms minimum spanning
tree and connected components with
This operation deletes a node from the binary
examples.
tree.
Answer : May/June-18 Q5 [OU]
3. Traversal
This operation is the process of visiting each Minimal Spanning Tree
node in a binary tree. A tree is defined to be an undirected, acyclic and
4. Merge connected graph or simply, a graph in which there is only
one path connecting each pair of vertices.
This operation combines two small binary
trees to form a larger binary tree. Assume that there is an undirected connected
graph G, then a spanning tree is a subgraph of G that
Q4. What are the various tree traversals?
contains all the vertices of G.
Answer : Model Paper-II, Q8
A minimum spanning tree is a spanning tree, that
Tree traversal is one of the most popular has weights with the edges and the total weight of the tree
operation performed on tree data structures. (the sum of the weights of its edges) is at a minimum.
The process of visiting each node of a tree in Example
some specific order is called tree traversal. The tree 2 2 2 2
can be traversed in following three ways, 4
3 5 3 4 3 4
1. In-order traversal 6

2. Pre-order traversal 1 1 1
(a) A Graph G (b) Three (of the many possible) S panning Trees from Graph G
3. Post-order traversal.
Figure
1. Inorder Traversal
2
Inorder traversal is performed using the
following steps, 3
1. Traverse the left subtree
1
2. Process the root node The Minimum
minimum spanning tree of Graph G G
Figure: The Spanning Tree of Graph
3. Traverse the right subtree.
Connected Components
2. Preorder Traversal
The connected components of a graph is defined
Preorder traversal is performed using the follow- as a set of nodes that are connected in pairs with the
ing steps, help of edges. The node pairs are connected only if they
1. Process the root node belong to same component.
2. Traverse the left subtree in pre-order Example
3. Traverse the right subtree in pre-order. a
3. Postorder Traversal
Postorder traversal is performed using the following
steps, b c
1. Traverse the left subtree
2. Traverse the right subtree
d
3. Process the root node.

109 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
The connected components for above graph are, 2. Decision Tree
a Decision tree is used to arrange the output of
several decision in the desired order i.e., in the form of
a tree. It contains root node, internal nodes,leaf nodes.
Internal nodes holds the conditions to be checked. The
b c tree is classified beginning at the root to the leaf node.
3. Huffman Coding
Huffman coding is the one of the best and
d important applications of binary tree in communication.
For example, consider the transmitting of text. Firstly,
Figure: Connected Component Using DFS
the message should be encrypted by using 0 and 1s
a i.e., each of the alphabet should be represented with 0s
and 1s binary code sequentially. The code given to an
alphabet should be unique and each alphabet should be
assigned with a code of length 5 as 24 < 26 < 25. Then
b c the transmitted message at receiver end is decrypted
in to alphabets and then the message is recognized by
the receiver. The message may consists of n number
of letters, from which some letters may appear many
d
number of times while other not appear frequently. So,
Figure: Connected Component Using BFS the most frequently occurred letters are represented with
Q7. Briefly describe about the properties of a short frequencies and the less frequently occurred letters
binary tree. are represented with long frequencies.

Answer : Nov./Dec.-17, Q5 [OU] 4. Game Trees


The following are the properties of a binary tree, Game trees is the most exciting application of
binary tree in games such as chess, nim, go, checkers,
Property 1: A binary tree with ‘n’ vertices must
tic-tac-toe and so on. The game is explained by using
contain exactly (n – 1) edges.
the tic-tac-toe game.
Property 2: If the height of a binary tree is h (where h
≥ 0) then the tree must contain at least h Q9. Write the algorithm for post order travers-
and atmost 2h – 1 nodes. al on a binary tree and give an example.
Property 3: The height of a binary tree with ‘n’ vertices Answer : June/July-19, Q6 [OU]
is atmost ‘n’ and at least [log2(n + 1)]. Post-order traversal is performed using the
Property 4: The total number of binary trees possible following steps,
1 2n 1. Traverse the left subtree
with n nodes is Cn
n+1
2. Traverse the right subtree
Property 5: A complete binary tree with n nodes
3. Process the root node.
contains n/2 internal nodes.
Algorithm
Q8. What are the binary tree application?
Nov./Dec.-19, Q5 [OU] Post Order Traversal (Recursive)
OR Procedure post-order(R)
What are the applications of Binary trees? Step 1: [check if the tree is empty by verifying root
pointer R]
Answer : (Model Paper-I, Q9 | May/June-19, Q3 [MGU])
if R == NULL
There are several applications of binary tree such
as Expression tree, Decision tree, Huffman’s Coding and print “tree is empty”
Game trees. port
ant Like Wa
ter Step 2: if leftptr(R) ≠ NULL then
Im
1. Expression Tree Call post-order(leftptr(R))
Expression tree is binary tree Step 3: if rightptr(R) ≠ NULL
that is used to store and represent the Call post-order(rightptr(R))
arithmetic expressions. It consists of leaf Step 4: print data(R)
nodes and internal nodes. The operands Step 5: return
(such as constants or variables) are represented as leaf nodes
Example
and operators are represented as internal nodes (or branch
nodes). For answer refer Unit-III, Page No. 112, Q.No. 11.

Publishers and Distributors Pvt. Ltd. 110


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Q10. Construct a binary tree using the following two traversals.
Inorder D B H E A I F J C G
Preorder A B D E H C F I J G
Answer : Nov./Dec.-18, Q5 [OU]
Given that,
If I Don’t Come,
Inorder D B H E A I F J C G My Method Will Come
Preorder A B D E H C F I J G
In preorder traversal of a binary tree, the root node is traversed first. So, the first value in the preorder traversal
gives the root of the binary tree. Then the left subtree followed by the right subtree are traversed.
In the inorder traversal, the left subtree is traversed initially and then the root is visited. Finally, the right
subtree is traversed.
A binary tree can be constructed from the given preorder and inorder traversals. Consider the above given
data, where the first element in preorder is ‘A’, so the element ‘A’ is the root node. The elements before ‘A’ in the
inorder list i.e., (DBHE) becomes the left subtree and the elements after ‘A’ in the inorder list i.e., (IFJCG) becomes
the right subtree. This can be shown in figure (a).
A

In: DBHE In: IFJCG


Pre: BDEH Pre: CFIJG
Figure (a)
In the left subtree, the first element in preorder list is ‘B’. So, ‘B’ becomes the root node. The elements on
the left side of ‘B’ in the inorder list i.e., (D) becomes the left subtree and the elements on the right side of ‘B’ in
the inorder list i.e., (HE) becomes the right subtree. This can be shown in figure (b).
A

B In: IFJCG
Pre: CFIJG

In: D In: HE
Pre: D Pre: EH

Figure (b)
Now, consider the left subtree of node B, the only element in preorder is ‘D’. So, ‘D’ becomes the leaf node.
But, in the inorder list, there is only element i.e., ‘D’. So both left subtree and right subtree cannot be formed. This
can be shown in figure (c).
A

B In: IFJCG
Pre: CFIJG

D In: HE
Pre: EH

Figure (c)
Now, consider the right subtree of node ‘B’, the first element in preorder list is E. So, ‘E’ becomes the root node
of the right subtree. In the inorder list, the elements on the leftside of ‘E’ i.e., (H) becomes the left subtree of ‘E’ and since
there are no elements on the rightsides of ‘E’, there is no right subtree for ‘E’. This can be shown in figure (d).
A

B In: IFJCG
Pre: CFIJG

D E

Figure (d)
Hence, the left subtree of node ‘A’ is completed.

111 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Now, consider the right subtree of root node ‘A’. In the right subtree, the first element in preorder is ‘C’. So,
‘C’ becomes the root node. In the inorder list, the elements on leftside of ‘C’ i.e., (IFJ) becomes left subtree and the
element on rightside of ‘C’ i.e., ‘G’ becomes right subtree. This can be shown in figure (e).
A

B C

In: IFJ In: G


D E
Pre: FIJ Pre: G

Figure (e)
Now, consider the left subtree of node ‘C’. The first element in the preorder i.e., ‘F’ becomes root node. In
the inorder list, the elements on the leftside of ‘F’ i.e., (I) becomes left subtree and the elements on the rightside of
‘F’ i.e., (J) becomes right subtree. This can be shown in figure (f).
A

B C

D E F In: G
Pre: G

H I J

Figure (f)
Now, consider the right subtree of node ‘C’, the only element in preorder is ‘G’ so it becomes leaf node. In
the inorder list, there is only one element i.e., ‘G’. So both left subtree and right subtree cannot be formed. This
can be shown in figure (g).
A

B C

D E F G

H I J

Figure (g)
Hence, the right subtree of node ‘A’ is completed and figure (g) gives the final binary tree constructed for
the given preorder and inorder lists.
Q11. Construct the binary tree from following:
In order 8,4,10,9,11,2,5,1,6,3,7. Find post order traversal.
Answer : Nov./Dec.-17, Q3 [MGU]
If I Don’t Come,
Given that, My Method Will Come

Pre-order traversal 1 2 4 8 9 10 11 5 3 6 7
In-order traversal 8 4 10 9 11 2 5 1 6 3 7

Publishers and Distributors Pvt. Ltd. 112


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
A binary tree can be constructed based on the Step 5
given in-order and pre-order lists. Consider the given
pre-order list in which 1 is the first element and there-
fore it becomes the root node. The elements before ‘1’
in the in-order list i.e., 8, 4, 10, 9, 11, 2, 5 becomes the
left subtree and the elements after ‘1’ in the in-order list
i.e., 6, 3, 7 becomes the right subtree. This process is
continued for each element in the post-order list until
the complete tree is constructed.
Step 1

Step 6

Step 2

Step 3

Therefore, from the above binary tree, the post


order traversal is,
8, 10, 11, 9, 4, 5, 2, 6, 7, 3, 1.
Q12. Define graph and explain graph represen-
tation. (Model Paper-II, Q9 | Nov./Dec.-19, Q6 [OU])

OR
Describe the adjacency matrix and ad-
Step 4 jacency list graph representations with
example.
(Refer Only Topics: Adjacency Matrix, Adjacency List)
Answer : Nov./Dec.-17, Q6 [OU]

Graph
A graph is defined as G = (V, E) Hey!
where, Don’t
escape
(i) V is the set of elements called from
nodes or vertices or points. me

(ii) E is the set of edges of the graph identified with


a unique pair (U, V ) of nodes.
Here (U, V) pair denotes that there is an edge
from node U to node V.

113 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Representation of Graph Q14. Briefly discuss connected graph.
The graph can be represented in three different Answer : Nov./Dec.-19, Q5 [MGU]
ways. They are as follows, Connected Graph
(a) Adjacency Matrix A graph is said to be connected if there exists a
An adjacency matrix A = (aij) of graph G is defined as, path between any two vertices U and V. Otherwise the
1 if Vi is adjacent to V j
aij 
graph is disconnected.
Example
0 otherwise
In case of directed graph, “Vi is adjacent to Vj” A B
means that there is a directed edge from Vi to Vj.
(b) Adjacency List
In adjacency list representation of a graph,
G = (V, E), each vertex of a graph is represented by
C D
an adjacency list. The adjacency list corresponding to
vertex ‘i’ contains all vertices that are adjacent to ‘i’ in
‘G’. In adjacency list representation, each adjacency list Figure: Connected Graph
is maintained as a chain so it is called linked adjacency The graph shown above is connected graph
list representation. because there is a path from each vertex.
(c) Adjacency Multilists path A to B: A → B
Adjacency multilists are the lists in which nodes A to C: A → B → D → C
may be shared among multiple lists. In adjacency
multilists, for every edge there is exactly one node. This A to D: A → B → D
node is present on the adjacency lists for the two nodes Similarly, every node has a path to other node
incident upon it. which can be verified from the graph.
Q13. Write short notes on, Q15. Write short notes on,
(i) Directed graph (i) Depth first search
(ii) Undirected graph. (ii) Breadth first search.
Answer :
Answer :
(i) Directed Graph
(i) Depth First Search
A graph in which every edge is directed is known
as a directed graph. In this method, we start from a given vertex V
Example in the graph. We mark this vertex as visited. Now any
of the unvisited vertex adjacent to V is visited. Then
B
neighbour of V is visited. This process is continued until
no new node can be visited. Now we backtrack from the
A C path to visit unvisited vertices if any left. Stack is used
to keep track of all nodes adjacent to a vertex.
D (ii) Breadth First Search
Figure: Directed Graph In this method we start with given vertex V and
Here the directed edge is shown by means of visit all the nodes adjacent to V from left to right. Data
arrows which also shows the direction. structure queue is used to keep track of all the adjacent
(ii) Undirected Graph nodes. The first node visited is the first node whose
A graph in which every edge is undirected is successors are visited.
known as an undirected graph. Q16. Explain how to represent the following
Example graph using Inverse Adjacency List.

1 2 3
A E C
Answer : Nov./Dec.-18, Q6 [OU]

Inverse adjacency list can be defined as a


D
collection of lists, where each and every vertex in the
Figure: Undirected Graph list contains another list associated with it.

Publishers and Distributors Pvt. Ltd. 114


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Given that, In order to search a pair with the key K, first we
find f(K) and determine whether a pair is at f(K) posi-
tion in the hash table. If it is not present at f(K) then we
1 insert the pair at f(K) else if it occurs f(K) then we find
2 3
the desired pair that can be deleted if required.
Figure: Graph Properties of Hash Function
The inverse adjacency list for the graph is, The properties of hash function are as follows,
Vertex
Null 1. It is easy to compute
1
2 2. Each cell has a unique (distinct) key.
1 Null
3 Q19. Write a short note on,
2 1 Null
(a) Open hashing
Figure: Inverse Adjacency List
(b) Closed hashing.
Q17. Write about Prim’s algorithm.
Answer : Model Paper-III, Q9
Answer : Model Paper-III, Q8

The Prim’s algorithm is very much similar to (a) Open Hashing


Dijkstra’s algorithm for finding shortest paths. In this type of hashing, the hash table stores a
An arbitrary node is chosen initially as the tree set of pointers (rather than data elements), where each
root (note that in an undirected graph and its spanning pointer points to a separate linked list. The data ele-
tree, any node can be considered as the tree root). The ments are stored in the nodes of these linked lists. For
nodes of the graph are then appended to the tree one at each element K, hash function (hf (k)) in applied, which
a time until all nodes of the graph are included. gives the hash code (index) of a particular bucket (cell)
The node of the graph added to the tree at each in the hash table. The element is stored in the linked list,
point is the node which is adjacent to a node with which is associated with that bucket (cell).
minimum weight. The arc of minimum weight becomes a
tree arc connecting the new node to the tree. When all the (b) Closed Hashing
nodes of the graph have been added to the tree, a minimum In this type of hashing the data element are stored
spanning tree has been constructed for the graph. with in the hash table. For each element K hash functionh
Q18. Write short notes on hashing and hash f(K) is applied and the element is stored at index(or hash
function. Model Paper-I, Q8 code) returned by hf( ). The different type of open ad-
OR dressing schemes are,
What is Hash Function? (i) Linear probing
(Refer Only Topics: Hash Function, Properties (ii) Quadratic probing
of Hash Function)
(iii) Double hashing.
Answer : Nov./Dec.-18, Q3 [MGU]

Hashing Q20. Explain the hash function with any two


implementation methods.
Hashing is a technique that
makes use of a hash function for Answer : May/June-18 Q6 [OU]
mapping pairs to the corresponding The implementation methods used by hash func-
(entries) positions in a hash table.
tion are as follows,
Ideally a pair ‘P’ with a key ‘K’ is Keep an eye on me
stored at a position f(K) by the hash (i) Division Method
function ‘f’. Each hash table position can store one pair.
One of the first hashing function and the most
Hash Function widely used concept which is defined as,
It is a function that is used to map the dictionary
H(X) = (X mod m) + 1
pairs to the corresponding entries in the hash table.
If the dictionary pair is ‘pair’ and if it consists of For some integer divisor m, the operation mod
the key ‘key and if ‘f’ denotes the hash function then the denotes the modulus of X. In this item X mod m refer
pair “pair” is stored at f(key) position in a table. to the modulus obtained after dividing X by m.

115 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Example 1
X = 25, m = 12
H(25) = (25 % 12) + 1
=1+1=2
So in the second location, value of X should be stored in hash table.
In mapping keys to address, there may be a chance to lose the uniformity by placing two different elements
at the same location.
Example 2
Cluster of keys 2300, 2301, . . . . and 2113 then these keys are mapped using the function (X mod 35) which
yields address as 7, 8, . . . . and 20. There are many collisions in this cluster i.e., mapping two distinct elements into
a single location as their remainder when divided by 35 yields the same result.
To overcome this collision we can use prime numbers which are large.
(ii) Module-division Method
In this method of hashing, the key element is divided by the size of the array and the obtained remainder is
used for the address. So, the hash method is,
address = key % arraysize
Example
If key = 25 and arraysize = 12
Then the address = 25%12
\ address = 1

Publishers and Distributors Pvt. Ltd. 116


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III

P a r t- b E S S AY Q u e s t i o n s a n d A n s w e r s

3.1 Trees

3.1.1 Introduction, Representation of a General Tree


Q21. Define tree. Explain the terminologies associated with it.
Answer :
Tree
A ‘tree’ is a non-linear data structure represented in a hierarchical manner. It contains a finite set of elements
called ‘nodes’. These elements connected to each other using a finite set of directed lines called ‘branches’.
Example
A

B C

Keep an eye on me
D E F

Figure: Tree
Terminologies Associated with Trees
1. Empty Tree
It is a tree with zero number of elements. It is also called as null tree.
2. Root Node
It is the top most node present in the tree. All the other nodes of the tree are either directly or indirectly
connected to the root node. In the example figure, A is the root node.
3. Parent Node
It is the node from which a tree or subtree is extended. It can also be defined as a node with child/children.
In the example figure, A is the parent of both B and C.
4. Children Node
It is the node linked or extended from the parent node. Each node in a tree has zero, one or more child
nodes. In the example figure, D and E are the children nodes of B, F is the child node of C, B and C are
the children node of A.
5. Terminal Node or Leaf Node
It is the node with no children. It the example figure, nodes D, E and F are the leaf nodes.
6. Branch Node or Internal Node
It is the node having atleast one child. In the example figure, nodes A, B and C are branch nodes.
7. Subtree
It is a connected structure following the root of the tree. It is a tree that extends from a node.
Example
A

B C

Subtree D E F Subtree

Figure: Subtree

117 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
8. Degree 12. Depth or Level of Node
The degree of a tree refers to the highest level It is the length of its path from root to that node.
of any of the nodes within that tree. A node’s Example
degree is the number of its children.
A
Example
Level-3 A
B C
A = Root node
Level-2 (B, C) (D, E, F) and (G, H) = Siblings
B C
B = Parent of D, E, F
C = Parent of G, H D
Degree of node B = 3
Level-1 D E F G H Degree of node C = 2
Degree of tree = 3
E

Figure The depth of ‘E’ in the tree is 3.


In the above example, the degree of the tree is 3 13. Height
because, here, the highest level of the node is 3
(i.e., node B). It is the length of the path from root node to a
node in the lowest level. In the example figure,
9. Edge the height of the tree is 2.
It is a line connecting two nodes in a tree. Q22. Explain how a general tree is represented.
Example Answer :
A General Tree
A general tree can be represented either using a
sequential organization or a linked organization. For a
B C generalized linked list, a node must have varying fields
based on the number of branches. The following figure
Here, AB and AC are two edges shows representation of node structure.
10. Path
Data Link 1 Link 2 . . . . Link n
It is the sequence of edges from starting/source
node to ending/destination node. It exists from Figure: Node Structure with Fixed Length
all parent nodes to children nodes. Here, the node with “Data” is the root node of
Example the tree.
It can also be represented in the form of linked
A
list.

D Data
B Link
Tag of 1
Link (next)
C (down)

Here, there are two paths from A to D. Example


Consider the following tree,
They are, A → B → C → D and A → D.
11. Path Length A

It is the total number of edges in a path.


Example
B C D
A

B D F I H J
E
G
C

Here, the length of path A → B → C → D is 3. K

Publishers and Distributors Pvt. Ltd. 118


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
This tree is represented as list in the below manner.
0 A 1 1 1 0

0 C 0 G 0 0 D 0 I 1 . 0 J 0

0 H 0 K 0

0 B 0 E 0 F 0

Figure: List Representation


In the list representation, initially the root node A is placed in the list. Then another three linked lists are
created for the subtrees with parent nodes B, C and D. From these nodes three separate linked lists are created
for the three subtrees [i.e., (B, E, F), (C, G), (D, I, J, K)] and linked to the root node list.
Q23. Explain various ways of representing trees.
Answer : Model Paper-I, Q17(a)

There are three ways of representing trees. They are,


1. Linked representation
2. Array representation
3. Binary tree representation.
1. Linked Representation of Trees
The two ways of representing a node structure in linked representation are,
(i) Fixed length node
(ii) Variable length node.
(i) Linked Representation of a Tree having Fixed Length Node
This method restricts the number of children for a node. Consider, the maximum number of children for
a node is ‘n’. Then, the representation of node structure is shown in figure (1).
Data Link 1 Link 2 Link n
Figure (1): Node Structure for Fixed Length Node
Here, the data forms the root node for the tree. The disadvantage of this representation is that, the memory
occupied by the null links is wasted.
Example
Linked representation of a tree having fixed length node is as shown in figure (2).
1

2 3 – –

Null
4 – – 5 – links

6 – –

Figure (2): An Example of Linked Representation of a Tree using Fixed Length Node

119 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
(ii) Linked Representation of a Tree having Example
Variable Length Nodes A
In this type of representation, the length of
a node in a tree depends on the number of
B C D
children it possesses which is not fixed. To
implement this kind of tree, nodes that have the
following structure is used. E F G

DATA Size ‘N’ Link 1 Link 2 Link n


H
Figure (3): Node Structure of Variable Length Node
Figure (6): Example Tree
Here, the DATA forms the root node for the DATA LEFTCHILD SIBLING
tree length indicating the number of links that
a node possesses. 1 A 2 0
Example 2 B 5 3
Linked representation of a tree having variable 3 C 7 4
size node.
4 D 0 0
1
5 E 8 6
2
6 F 0 0

3 4 5 7 G 0 0

8 H 0 0
6

Figure (4): Example Tree Figure (7): Representation of a Tree using Arrays
3. Binary Tree Representation of Trees
Data Size Link
Tree can be represented uniquely using a
1 1
binary tree. It is one of the organized and effective
way for the computer implementation.
The correlation between a general tree ‘G’ and
2 3
a binary tree ‘B’ is as given below.
(a) A root node of binary tree ‘B’ will be same as
the root node of general tree ‘G’.
3 0 4 1 5 0
(b) All the nodes present in a binary tree ‘B’ will
also be present in general tree ‘G’.
6 0
(c) The left-most child, next-right sibling is the
Figure (5): Equivalent Linked Representation of Tree in rule followed by parent-child relationship i.e.,
Figure (4) the first child of a node N in the general tree ‘G’
becomes leftchild in binary tree ‘B’. Similarly,
This variable size representation of a node also sibling becomes the right child.
has the same disadvantage as that in linked
representation of a tree having fixed length To make the binary tree equivalent to a general
node i.e., wastage of memory. Since, it is tree ‘G’, The steps given below must be followed.
required to store the size of node in a separate 1. The siblings that are at the same level are
field, the wastage of memory occurs. connected using links.
2. Array Representation of Trees 2. The links starting from every node, except the
left most link are to be deleted.
Trees can also be represented using arrays.
This type of representation requires three arrays i.e., 3. For a node N, the selection of left child and
DATA, LEFTCHILD and SIBLING. The information right child is as follows,
that a node contains is stored in the array ‘DATA’, (i) The node which is immediately below the node
the index of left child of a node is stored in the array ‘N’, is taken as left child.
‘LEFTCHILD’ and a node which is immediate sibling (ii) The node which is immediately right of the node
to the current node is stored in the array ‘SIBLING’. ‘N’ and lies on the same level is taken as right
Here, NULL links are denoted by ‘0’. child.

Publishers and Distributors Pvt. Ltd. 120


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Example A Root

A
B C
Right subtree of A
Left subtree of A
B C D
D E F
E F G
A binary tree (a)
H Figure (1): Binary Tree
Figure (8): General Tree ‘G’ The nodes of the given binary tree are A, B, C,
A D, E, F.
(ii) Full Binary Tree
B C D
A full binary tree is a binary tree in which
E F G there is one node at root level 0(20 = 1), two nodes at
level 1(21 = 2), four nodes at level 2 i.e., (22 = 4) and so
H on and has (2l) nodes at level l.
Figure (9): After First Step Consider the following binary tree,
A 0
A

B
1 2
B C

E C 6
3 4 5
D E F G
H F G D
Figure (2): Full Binary Tree showing the Order in which
Figure (10): After Second Step Nodes are Associated with the Tree
DATA LCHILD RCHILD
A
If the number of nodes in a full binary tree is
known, then depth of the tree can be computed by the
equation,
B C D
n = 2d+1 – 1

E F G
Thus depth, d is given by,

d = log(n +1) – 1
H
For example, if there are 31 nodes in a full
Figure (11): Binary Tree Representation with Nodes binary tree, then the depth d will be,

3.1.2 Binary Tree Introduction d = log(31 + 1) –1


= log 32 – 1
Q24. Define the following terms,
= log225 – 1
(i) Binary tree
= 5 log2 2 – 1
(ii) Full binary tree
=5–1=4
(iii) Complete binary tree.
Answer : \ Depth d for n = 31 is 4.
(i) Binary Tree (iii) Complete Binary Tree
A binary tree ‘T’ is defined by finite set of A variation of full binary tree is complete
elements called nodes such that, binary tree in which if a binary tree has depth d then,
(a) A binary tree is empty or 1. Any node n at level less than d – 1 has two children.
(b) It consists of a node called ‘root’ which 2. For any node n in the tree with right descendant
includes two binary trees called left at level d, n must have a left child and every left
subtree and right subtree of the root. descendant of node n is either a leaf at level d or
Figure (1) represents a binary tree, has two children.

121 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Example
Consider the binary tree shown in figure (3),
A Level 0

B C Level 1

D E F G Level 2

H I Level 3

Figure (3): Complete Binary Tree


The depth of the tree is, d = 3.
The above node is said to be complete binary tree, when
1. Nodes at level less than d – 1 i.e., at d = 0 and d = 1 have two children.
2. The node D has right descendant at level d i.e., (level 3) and D has left child and also it is a leaf node.
The depth d of a complete binary tree T with n nodes is given by, d = [log2n + 1]
\ n = 2d –1
So the depth d of tree with n = 64 is,
d = log264 +1
= log226 +1
= 6 log22 +1
=6+1
\ d=7
Hence, it is a complete binary tree with depth 7.
Q25. What are the properties of a binary tree? Also, differentiate between a tree and binary tree.
Answer :
Properties of Binary Tree
The following are the properties of a binary tree,
Property 1
A binary tree with ‘n’ vertices must contain exactly (n – 1) edges.
Property 2
If the height of a binary tree is h (where h ≥ 0) then the tree must contain at least h and atmost 2h – 1 nodes.
Property 3
The height of a binary tree with ‘n’ vertices is atmost ‘n’ and at least [log2(n + 1)].
Property 4
1
The total number of binary trees possible with n nodes is 2n
Cn
n+1
Property 5
A complete binary tree with n nodes contains n/2 internal nodes.
Property 6
A complete binary tree with n nodes contain (n + 1) null nodes.
Property 7
If a binary tree contains n0 leaf nodes and n2 nodes (2 degree nodes) then n0 = n2 H.

Publishers and Distributors Pvt. Ltd. 122


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Differences Between Trees and Binary Trees

S.No. Trees S.No. Binary Trees


1. Trees are non-linear data structures represented 1. Binary trees are trees which contain nodes and
in a hierarchical manner. each node contains name of data and link to
other tree nodes.
2. A tree is a finite non-empty set of elements. 2. A binary tree is a finite set of elements that can
be empty.
3. Every individual element in a tree can have 3. Every element in a binary tree has exactly two
any number of subtrees. subtrees i.e., right subtree and left subtree.
4. The subtrees of each element in a tree are 4. The subtrees of each element in a binary tree
unordered. are ordered.
5. 1 5. 1

2 3
2 3

4 5 6 7 8
4 5 6 7

Figure: Binary Tree


9 10

Figure: Tree

3.1.3 Binary Tree Abstract Data Type


Q26. Explain in detail about Binary Tree ADT.
Answer : Model Paper-I, Q17(b)
A binary tree ADT is defined by finite set of elements, called nodes such that,
(a) A binary tree is empty or
(b) It consists of a node called root together with two binary trees left sub-tree and right-subtree. The left sub-
tree elements are less than root node and right sub-tree elements are greater than root node.
The various ADT operations that can be performed on binary tree are,
1. create( )
2. Boolean IsEmpty( )
3. make BT( )
4. left child( )
5. right child( )
6. elementData(btree)
1. create( )
This method is used to generate an empty binary tree.
2. Boolean IsEmpty(btree )
This method is mainly used to check whether the binary tree (btree) contains root node or not. If binary tree
is empty, it returns true, else it returns false.
3. make BT(btree 1, item, btree 2)
This method makes a binary tree (btree) with left subtree (btree 1), root element (item) and right subtree
(btree 2).
4. left child(btree)
This method checks whether the tree is empty or not. If the binary tree (b tree) is empty, then it returns an
error. Otherwise it returns left child of btree.
5. right child(btree)
This method checks whether the tree is empty or not, if the binary tree (btree) is empty, then it returns an
error, else this method will return right subtree of the binary tree(b tree).

123 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
6. element Data (btree) 7. Compare
This method checks whether the created binary This operation is performed for the comparison
tree is empty or not. If the binary free is not of two binary trees.
empty, returns root node value of the binary tree. 8. Find
Otherwise returns an error. This operation is performed to find duplicate of
An example for abstract data type Binary Tree a binary tree.
is as follows:
class Node
3.1.4 Implementation of Binary Trees
{ Q28. Explain various implementations of
public : binary tree.
char values ; Answer :
Node *Left ; The following are the two different
Node *Right ; implementations of a binary tree
};
1. Array implementation
class Tree
2. Linked list implementation.
{
private: 1. Array Implementation
Node *RootNode ; The elements of a binary tree can be
public : implemented in the form of an array. The elements
are stored at the consecutive locations relative to the
Tree( )
numbers assigned to them.
{
Root Node = NULL; Example
}; Consider a complete binary tree,
Node *GetN( ); A
void InsertNode(Node*);
void DeleteNode(Node*); B C
};
Q27. List the operations that can be performed D E F G
on a binary tree.
Answer : Figure (a): Complete Binary Tree with Missing Elements
The operations that can be performed on a In figure (a), there are seven elements A, B,
binary tree are, C, D, E, F, G. A number is assigned to every node
1. Insertion by moving from left to right in a binary tree. This is
This operation adds a node to the current shown in figure (b).
binary tree. A 1
2. Deletion
This operation deletes a node from the binary B 2 C 3
tree.
5 7
3. Traversal 6
D 4 E F G
This operation visits each node in a binary tree.
Figure (b): Nodes of a Binary Tree with the Numbers
4. Merge
Assigned to them
This operation combines two small binary
trees to form a larger binary tree. Based on these numbers, an array is constructed
5. Creation by storing every numbered node at the corresponding
array location as shown below,
This operation is the process of creating a
binary tree. A B C D E F G
6. Copy Array location: 1 2 3 4 5 6 7
This operation is performed for copying a
binary tree. Figure (c): Array Representation of a Binary Tree

Publishers and Distributors Pvt. Ltd. 124


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
However, the array representation of a binary tree Q29. Define binary search tree. Construct a
with ‘n’ nodes require an array size of 2n, including the binary search tree and explain the opera-
array location 0. The array size of binary trees is large tions inserting a node, searching for a
when every node (excluding the root node) is the right/left key, deleting a node with examples.
child of its parent node.
Answer : Nov./Dec.-17, Q11(a) [OU]
Such type of binary trees are known as right/
left skewed binary trees, which is shown in figure (d). Binary Search Tree
Don’t Think
A A binary search tree is I am Complex

a non-linear data structure that


B provides very quick access to
data and with more constraints. A
C binary tree ‘Bt’ is a binary search
Figure (d): Right-Skewed Binary Tree tree if each node ‘x’ of Bt satisfies
2. Linked List Implementations the following criteria,
In this implementation, each node of binary 1. The node values of the left sub-tree of ‘x’ are less
tree is represented as shown in figure below, than the value of ‘x’.
2. The node values of the right sub-tree of ‘x’ are
LLINK DATA RLINK
greater than the value of ‘x’.
NODE
3. The left sub-tree and right sub-tree of binary
v LLINK stores the address of left child.
search tree again a binary search tree.
v RLINK stores the address of right child.
The following figures shows some binary search
v LLINK stores NULL when it does not have left child. trees.
v RLINK stores NULL when it does not have
right child.
v DATA field stores the actual data of the node.
v A pointer variable ROOT represents the root of
the tree.
Example
Figure: Binary Search Tree, Order is Numerical
A

B D

C E Figure: Binary Search Tree, Order is Lexicographical


Figure (e): Binary Tree Operations of Binary Search Tree
The tree shown in figure (e) is represented 1. Inserting a Node
using linked list as, Insertion begins as a search would begin, if the
Root
root is not equal to the value, we search the left or right
subtrees as before. Eventually, we will reach an external
node and add the value as its right or left child, depending
A
on the node’s value. In other words, we examine the root
and recursively insert the new node to the left subtree if
the new value is less than or equal to the root or the right
B NULL NULL D
subtree if the new value is greater than the root.
Another way to explain insertion is that in order
NULL C NULL NULL E NULL
to insert a new node in the tree, its value is first compared
Figure (f): Linked Representation with the value of the root. If its value is less than the
root then it is compared with the value of the root’s left
In figure (f), there are 5 nodes and 6 null links. child. If its value is greater, it is compared with the root’s
So, if there are ‘n’ nodes then there will be (n + 1) right child. This process continues, until the new node is
NULL links. Hence, memory is being wasted in this compared with a leaf node, and then it is added as this
representation. node’s right or left child, depending on its value.

125 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Example Example

Consider the below binary search tree as, Consider the below search tree.

Figure
Figure: Binary Search Tree
If an element is to be searched in the binary search
After inserting a new element 40, the binary search tree the searching operation starts from root node. The
tree is, target node is compared with the root node. If matched,
the position of root node is returned. If root node is greater
than target node, then search operation is performed on
right subtree. If root node is less than target node, the search
operation is performed on left subtree.

Figure: Binary Search Tree After Inserting 40

After insertion of another element 15, the binary


search tree is,
Figure
Let the target node be 25 which has to be searched
in the above tree. Here root node is greater than target
node. Therefore, searching process is performed on right
subtree.

Figure: Binary Search Tree After Inserting 15

2. Searching for a Key

Searching a binary search tree for a specific value


is a process that can be performed both recursively and Figure
iteratively. The searching process begins by examining The target node is compared with the parent node
the root. If the searching value is matched with the root, of right subtree, when it is found to be greater than target
then the value is existed in the root. If it is less than root element. Therefore, searching operation is performed on
nodes, then the searching process is performed on left left subtree of that node. The element 25 is found at left
subtree. Similarly, if the value is greater than the root, child of right subtree, so the position of that node (i.e.,
then the value must be searched in right subtree. 25) is returned.

Publishers and Distributors Pvt. Ltd. 126


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
3. Deleting a Node
3.1.5 Binary Tree Traversals – Preorder,
There are several cases to be considered while Inorder, Postorder Traversals
deleting.
(i) Deleting a Leaf Q30. What are different traversal techniques
Deleting a node with no children is easy, as we for binary tree? Explain about them with
can simply remove it from the tree. good examples. Nov./Dec.-17, Q7(a) [MGU]
(ii) Deleting a Node with One Child OR
Delete it and replace it with its child. Define binary search tree. Explain pre-
(iii) Deleting a Node with Two Children order, in-order, post-order binary search
Suppose the node to be deleted is N. We replace the tree traversals with examples.
value of N with either its in-order successor (the (Model Paper-I, Q18 | May/June-18, Q11(a) [OU])
left-most child of the right subtree) or its in-order
OR
predecessor (the right-most child of the left subtree).
Once we find either the in-order successor Describe about binary tree traversal
or predecessor, replace it with N and then delete it. techniques.
Since either of these nodes must have less than two Answer : May-18, Q7(a) [MGU]
children (otherwise it cannot be the in-order successor
Binary Search Tree
or predecessor), it can be deleted using the previous
two cases. In a good implementation, it is generally For answer refer Unit-III, Page No. 125, Q.No.
recommended to avoid consistently using one of these 29, Topic: Binary Search Tree.
nodes, because this can unbalance the tree. Binary Tree Traversal Techniques
Example
A tree/binary tree traversal
Consider the below binary search tree, techniques traverses or visits each
node in a tree atleast once. Certain
operations are performed on the node I am a
Repeated

while traversing. Apart from this, the Question

nodes in a tree is traversed completely


by following linear ordering. Each
node and its respective subtree are
treated in the same way while traversing.
If ‘L’ represents moving left to the node, then ‘V’
represents visiting the node and ‘R’ represents moving
Figure: Binary Search Tree right to the node then, the six possible combinations of
traversing are LVR, LRV, VLR, VRL, RVL and RLV.
After deleting a node 15, the binary search tree is, If the traversal technique is done from left to right, then
the possible combinations are LVR, LRV and VLR with
respect to the positions of V with L and R the names are
allocated to these as inorder, preorder and postorder.
The Binary tree traversal technique is a method
which visits all the nodes of the tree. Binary tree is a
non-linear data structure which supports the following
three traversal techniques.
1. Inorder traversal
2. Preorder traversal
Figure: Binary Search Tree After Deleting 15 3. Postorder traversal.
After deleting the node 13, the binary search tree is, 1. Inorder Traversal
Inorder traversal is used to display all the nodes
in the non-decreasing order. In this traversal, left child is
visited first followed with the root node and the right child.
Inorder traversal is performed using the
following steps,
(i) Traverse the left subtree
(ii) Process the root node
Figure: Binary Search Tree After Deleting 13 (iii) Traverse the right subtree.

127 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Algorithm for Inorder Traversal (Recursive) There is no left subtree for E.
Procedure for inorder(R) C B A E LST F RST D RST
Step 1
[check if the tree is empty by verifying C B A E F D RST
root pointer R]
If R = = NULL
There is no left subtree and right subtree for F.
Print “tree is empty”
Step 2 C B A E F D LST G RST
if leftptr(R) ≠ NULL then
C B A E F D G
Call inorder(leftptr(R))
There are no left and right subtrees for G.
Step 3
print data(R) In order traversal for the tree is,
Step 4 C B A E F D G
if rightptr(R) = = NULL
The traversing of binary tree in order [LRN] is
Call inorder(rightptr(R)) diagrammatically shown as,
Step 5 A

return.
Example B
D

Consider the below given figure,


G
A
C E

B D
F

E G
C
Figure (2): Inorder Traversal
F Here in figure (2), side arrows in the dotted line
Figure (1) indicates that the node has been processed.
Inorder traversal for binary tree given in figure So, the inorder of the binary tree in the figure
(1) is obtained as follows, (2) is, C – B – A – E – F – D – G
LST A RST 2. Preorder Traversal
Where, LST is left subtree and RST is right Preorder traversal is used to display any given
subtree node before displaying its children node. In this
traversal, root node is visited first followed by the left
LST B RST A RST child and the right child.
Preorder traversal is performed using the
LST C RST B RST A RST following steps,
(i) Process the root node
(ii) Traverse the left subtree in preorder
C B RST A RST
(iii) Traverse the right subtree in preorder.
There is no left and right subtree for C. Algorithm for PreOrder Traversal (Recursive)
C B A RST Procedure for pre-order(R)
Step 1
There is no right subtree for B. [check if the tree is empty by verifying root
C B A LST D RST pointer R]
If R = = NULL
C B A LST E RST D RST
Print “tree is empty”
Step 2
C B A E RST D RST
print data(R)

Publishers and Distributors Pvt. Ltd. 128


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Step 3 The traversing of the binary tree in pre
if leftptr(R) ≠ NULL then order(NLR) is diagrammatically shown in figure (d).
A
Call preorder(leftptr(R))
Step 4 B D

if rightptr(R) ≠ NULL
Call preorder(rightptr(R)) C E G

Step 5
return. F

Example
Figure (4): Preorder Traversal
Consider the below given example,
The direction of arrow marks represents the
A order in which nodes are accessed.
A–B–C–D–E–F–G
B D
3. Postorder Traversal
C E G
In postorder traversal, the termination of the
children node is done before the termination of the
parent node. In this traversal, left child is visited first
F
(a)
followed by right child and the root node.
Figure (3) Postorder traversal is performed using the
The preorder traversal for binary tree in the following steps,
figure (3) is given by, (i) Traverse the left subtree
(ii) Traverse the right subtree
A LST RST (iii) Process the root node.
Where LST is left subtree and RST is right Algorithm for Post Order Traversal (Recursive)
subtree.
Procedure post order(R)
A B LST RST RST Step 1

[check if the tree is empty by verifying root
[There is no RST for B, C will be traversed next] pointer R]
A B C LST RST RST RST if R == NULL
print “tree is empty”
[There is no left subtree and right subtree for C.] Step 2
A B C RST RST if leftptr(R) ≠ NULL then
Call post-order(leftptr(R))
[There is not right subtree for B.] Step 3
A B C RST if rightptr(R) ≠ NULL
Call post-order(rightptr(R))
[Now traversing the RST of A] Step 4
A B C D LST RST print data(R)
A B C D E LST RST RST Step 5
return.
A B C D E RST RST Example
There is no left subtree for E. Consider the below given example,
A
A B C D E F LST RST RST

B D
A B C D E F G
E G
(There is no LST and RST for F) C

pre order traversal for the tree is, F


A B C D E F G Figure (5): Postorder Traversal

129 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Postorder traversal for binary tree given in the Q31. Define the binary tree and explain its prop-
figure (5) is obtained as follows, erties. Explain the binary tree traversal
techniques with example.
LST RST A
Answer : Nov./Dec.-19, Q11(a)(i) [OU]
Where, LST is left subtree and RST is right
Binary Tree
subtree Hey!
For answer refer Unit-III, Don’t
LST RST B RST A Page No. 121, Q.No. 24(i). escape
from
Properties of Binary Tree me
LST RST C B RST A
For answe refer Unit-III, Page
No. 122, Q.No. 25, Topic: Properties of Binary Tree.
[As C is a left subtree for B and no RST for B]
Binary Tree Traversal Techniques
C B RST A
For answer refer Unit-III, Page No. 127, Q.No. 30.
Q32. Explain various tree traversal operations
There are no left and right subtrees for C.
for the given example and write the
C B LST RST D A outputs,
Now right subtree of A is processed.
8
C B LST RST E RST D A
4 12

Process left subtree of D.


2 5 9 14
C B RST E RST D A
3 7 10

There is no left subtree for E. Answer :


The various traversal operations for the given
C B LST RST F E RST D A tree are,
(i) Pre-order traversal
Process right subtree of E.
(ii) In-order traversal
C B F E RST D A (iii) Past-order traversal.
(i) Pre-order Traversal
There are no left and right subtrees for F.
Given tree,
C B F E LST RST G D A

8
C B F E G D A

4 12
There are no left subtree and right subtree for
G. post order traversal for the tree is,
2 5 9 14
C B F E G D A
The traversing of a binary tree in post-order 3 7 10
[LRN] is diagrammatically shown in figure (6), The pre-order traversal for the binary tree is
A given by,
8 LST RST
D
B Where LST is left subtree and RST is right subtree.
8 4 LST RST RST
G
C E
8 4 2 LST RST RST RST
F
8 4 2 RST RST RST
Figure (6): Postorder Traversal

Publishers and Distributors Pvt. Ltd. 130


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Where LST is left subtree and RST is right
8 4 2 3 LST RST RST RST subtree.
LST RST 4 RST 8
8 4 2 3 5 LST RST RST
LST RST 2 RST 4 RST 8

8 4 2 3 5 RST RST
RST 2 RST 4 RST 8

8 4 2 3 5 7 RST 3 2 LST RST 5 4 RST 8

8 4 2 3 5 7 12 LST RST 3 2 RST 5 4 RST 8

8 4 2 3 5 7 12 9 LST RST RST


3 2 7 5 4 LST RST 12 8

8 4 2 3 5 7 12 9 10 RST 3 2 7 5 4 LST RST 9 RST 12 8

8 4 2 3 5 7 12 9 10 14 3 2 7 5 4 RST 9 RST 12 8

(ii) In-order Traversal 3 2 7 5 4 10 9 14 12 8


Inorder traversal for given binary tree is
Q33. Discuss with necessary functions about
obtained as follows,
Iterative inorder traversal.
LST 8 RST
Answer :
Where LST is Left subtree and RST is right Iterative Inorder Traversal
subtree.
In the inorder tree traversal operation, the
LST 4 RST 8 RST elements in the left subtree (L) are visited first then the
root node (N) is visited and later the right subtree(R) is
visited. i.e.,
LST 2 RST 4 RST 8 RST

2 RST 4 RST 8 RST

2 3 4 LST 5 RST 8 RST

2 3 4 5 RST 8 RST
Figure: Inorder Tree Traversal (LNR)

2 3 4 5 7 8 LST 12 RST This operation helps in arranging elements in


ascending order.
2 3 4 5 7 8 9 RST 12 RST Example
Consider the following binary search tree.
2 3 4 5 7 8 9 10 12 14
(iii) Post-order Traversal
The postorder traversal for given binary tree is
obtained by,

LST RST 8

131 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
The order in which the nodes in the binary search Q35. Construct a binary tree for the following
tree are stored in stack using inorder tree traversal preorder and inorder traversals. Explain
operation are, with a neat diagram,
Preorder A B D I E H J C F K L G M
Inorder DIBHJEAFLKCGM
Answer :
Preorder ABDIEHJCFKLGM
Inorder DIBHJEAFLKCGM
1; 5; 6; 11; 12; 16 In preorder traversal of a binary tree, the root node
Thus, with inorder tree traversal operation, the is traversed first. Therefore, the first value in the preorder
nodes in binary search tree are stored in stack in the traversal gives the root of the binary tree. Then, the left
ascending order. subtree followed by the right subtree are traversed in
The inorder tree traversal operation can be preorder.
implemented recursively and non-recursively.
For inorder traversal, the left subtree is traversed
Non-recursive Implementation
initially and then the root is visited finally right subtree
template<class T>
is traversed.
void BSTree<T> : : NonR_inorder( )
{ A binary tree can be built when preorder and
stack<BSTreeNode<T> *> s; inorder traversals are given. Consider the above given
BSTreeNode<T> *node = root; set, where the first element in preorder is A, therefore the
while(node! = 0) element A is the root node. The elements before A in the
{ inorder list (DIBHJE) becomes the left subtree and the
if(node –>rightchild) elements after A in the inorder list (FLKCGM) becomes
s.push(node –> rightchild); the right subtree. This can be shown as in figure (a).
s.push(node);
node = node –> leftchild;
}
node = s.pop( );
while(!s.empty( ) && node –> right = = 0)
{
visit(node); Figure (a)
node = s.pop( ); In the left subtree, the first element in preorder
} list is B and B becomes the root node and the elements
visit(node); on the left side of ‘B’ in the inorder list (DI) becomes
if(!s.empty( )) the left subtree and the elements on the right side of B
node = s.pop( ); in the inorder list becomes the right subtree.
else This explanation can be shown in figure (b).
node = 0;
}
Q34. Define Inorder traversal algorithm with
an example. Write a C++ member func-
tion to implement non-recursive inorder
traversal algorithm of a binary tree.
Answer : June/July-19, Q11(a) [OU]

Inorder Traversal
For answer refer Unit-III, Page No. 127, Q.No. Figure (b)
30, Topic: Inorder Traversal. Now, considering the left subtree of node B, the
first element in preorder is D. But in the inorder list, there
Non-recursive Implementation of Inorder Traversal
are no elements on the left of D, therefore a left subtree
for Binary Tree
cannot be formed. But there is an element on the right
For answer refer Unit-III, Page No. 132, Q.No. side of D i.e., I which becomes the right subtree of D.
33, Topic: Non-recursive Implementation. See figure (c).

Publishers and Distributors Pvt. Ltd. 132


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III

Figure (f)
Figure (c)
Considering the right subtree of node B, the first
element in preorder list is E and therefore E is the root
node of the right subtree. In the inorder list, the elements
left to E are H, J which form the left subtree of E and
there is no right subtree for E. See figure (d).

Figure (g)

Figure (d)
Now consider the left subtree of node E. The root
node is H as H is the first element in the preorder list.
In the inorder list (i.e., HJ), there is an element J to the
right of H and therefore it forms a right subtree for the
node H and it does not have a left subtree as there is no
element before H in the inorder list. See figure (e).
Figure (h)

Figure (e)
The above explanation can be applied to the right Figure (i)
subtree of node A. This process results in a unique binary Figure (i) is the resulting unique binary tree
tree that can be shown in the following figures. developed for the given preorder and inorder lists.

133 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Q36. Explain about properties of binary search Step 5: Insert 85
tree. Construct binary search tree for fol-
lowing:12,47,88,57,85,43,15,20. 12

Answer : Nov./Dec-17, Q7(b) [MGU]


47
Properties of Binary Search Tree
1. The key in the left child of a
node (if exists) is less than the If I Don’t Come, 88
key in its parent node. My Method Will Come

2. The key in the right child of a node (if exists) is 57


greater than the key in its parent node.
3. The left and right subtrees are again binary search 85
trees.
Construction of Binary Search Tree
Step 6: Insert 43
Given that,
12
12,47,88,57,85,43,15,20
Step 1: Insert 12
As 12 is the first element in the given sequence, 47
it is considered as the root node.
43 88
12

Step 2: Insert 47 57

Since 47 > 12, it is inserted as the right child of


the root. 85

12 Step 7: Insert 15

12
47
47
Step 3: Insert 88

12 43 88

15 57
47

85
88
Step 8: Insert 20
Step 4: Insert 57
12
12

47
47
43 88

88
15 57

57 20 85

Publishers and Distributors Pvt. Ltd. 134


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Therefore, the resultant binary search tree is, cout<<“Enter the elements:\n”;
for(n = 0; n < req; n++)
12
{
47
cin>>num;
insert(&t, num);
43 88 }
cout<<“\nInorder traversal is: ”;
15 57 inorder(t);
cout<<“\nPreorder traversal is:”;
20 85 preorder(t);
cout<<“\nPostorder traversal is:”;
Q37. Write a program to travel binary tree in postorder(t);
pre-order, post-order and in-order. //getch( );
Answer : Nov./Dec.-19, Q11(a)(ii) [OU] }
Program void insert(struct node **p, int num) // Insert function
#include<stdio.h> // Header file section {
#include<conio.h> if(*p ==NULL)
#include<iostream> {
#include<malloc.h> *p = (struct node*)malloc(sizeof
#define M 100 // Global declaration (structnode));
(*p) -> lt = NULL;
using namespace std;
(*p) -> info = num;
struct node
(*p) -> rt = NULL;
{
return;
struct node *lt;
}
int info; Solve Me with Concentration else
struct node *rt; {
}; if(num<(*p) -> info)
int main( ) // Main program section insert(&((*p) -> lt), num);
{ else
struct node *t; insert(&((*p) -> rt), num);
int req, n, num; }
void insert(struct node**, int); }
void preorder(struct node*); void inorder(struct node *t) //Inordertraversal
void postorder(struct node*); {
if(t!= NULL)
void inorder(struct node*);
{
t = NULL;
inorder(t -> lt);
cout<<“\nImplementation of binary tree
cout<<” “<< t -> info;
traversals \n”;
inorder(t -> rt);
cout<<“----------------------------------------------”;
}
cout<<“\nSpecify the number of items to
}
be inserted:”;
void preorder(struct node *t) // Preorder traversal
while(1)
{
{
if(t!= NULL)
cin>>req; {
if(req>=M || req<=0) cout<<” “<< t -> info;
cout<<“\nEnter number 1 to 100”; preorder(t -> lt);
else preorder(t -> rt);
break; }
} }

135 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
void postorder (struct node *t) // Postorder traversal Binary tree is also used to represent the prefix,
{ postfix expressions. To construct a tree when an infix
expression is provided, initially it is converted to postfix.
if(t!= NULL)
Let E be a token from the expression. An algorithm to
{ construct expression tree is as follows.
postorder(t -> lt); 1. Start.
postorder(t -> rt); 2. Get a token from E.
cout<<“ ”<<t -> info; 3. Create a node pr for the token.
} 4. If (symbol is operand) then
} push the node pr onto the stack.
Output 5. Else if (symbol is operator) then
5.1 rp = pop( ) (∴ lp & rp are the
pointers to left and right subtrees
respectively)
lp = pop( )
5.2 Add lp, rp to left and right of pr
respectively.
5.3 Make a tree, whose root is the operator,
and lp, rp are left and right children,
respectively.
5.4 Push node pr that is attached to left
and right subtrees of the stack.
3.1.6 Applications of Binary Trees Briefly
6. Repeat the steps 1-5 till the expression ends.
Q38. Explain in detail about the application of
7. Pop the pointer pr, which points to the root node.
binary trees.
8. Stop.
Answer : (Model Paper-II, Q18(a) | Nov./Dec.-19, Q9(a) [MGU])
An example of postfix expression to expression
Applications of Binary Trees tree is,
There are several applications of binary tree such E = pq × rs/+
as Expression tree, Decision tree, Huffman’s Coding and
Game trees. +
1. Expression Tree
Expression tree is
binary tree that is used to store × /
and represent the arithmetic
expressions. It consists of leaf
nodes and internal nodes. The
operands (such as constants or variables) are represented p q r s
as leaf nodes and operators are represented as internal
nodes (or branch nodes). Let E be the arithmetic Figure: Expression Tree for Postfix Expression ‘E’
expression. The expression tree for E is as follows, 2. Decision Tree
E = ((p × q) + (r – s))/(r – t) Decision tree is used to arrange the output of
/ several decision in the desired order i.e., in the form of
a tree. It contains root node, internal nodes,leaf nodes.
Internal nodes holds the conditions to be checked. The
tree is classified beginning at the root to the leaf node.
+ –
Consider the execution of a C++ program
as an example. The structure of a C++ program
× – r t contains pre-processor directives, global variables and
functions. The process of execution is depends up on
the given code. Mostly, every C++ program contains
p q r s
conditional statements (if, if-else), loop statement
(while), unconditional statements(for loop) other than
Figure: Expression Tree for ‘E’ input/output statements. The program execution depends

Publishers and Distributors Pvt. Ltd. 136


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
on the conditions. In case of conditional statements, ⇒ 3 × 50 × 5
say if statement, after testing the boolean expression, Each of
the statements followed by if statement are executed
otherwise statements followed by else statement are Each letter appeared 50 times
executed. The program can be executed through a Length is reduced by 3
decision tree. While execution of a C++ program root
is the main( ) function, that contains the code that will There is a problem using the variable length
always runs at the starting of the program. The statements coding i.e., when the sender transmits the message using
are executed depending on the condition. various lengths, how does the receiver divides the string
Different decision trees for a program structure into the sequences corresponding to the letter.
are as follows, An elegant procedure to construct an optimal
if statement Case statement While loop
binary tree defined by the Huffman is as follows,
False True
Executes
1. Arrange the data in a row in such a way that their
Then else ‘0’ times weights are in increasing order. Each character is
C1 C2 C3 C4 Cn
Executes the leaf node of a tree.
1 times

Executes 2. Select the two nodes with small weights.


2 times

Executes
3. Make a third node by combining the weights of
3 times two small nodes.
Figure: Decision Trees for a Program Structure 4. Repeat steps 2 and 3 until all the nodes on each
In a while loop, the body of the loop executes level are combined to create a single tree.
n number of times, depending on the conditions. The
advantages and disadvantages using decision tree are, The example to illustrate the above algorithm is
as follows,
Advantages
1. It is used for classification with less computations. a, b, c, d, e are nodes with weights 1, 4, 6, 7, 13
2. It is used to list all the possible decisions from respectively then the Huffman coding for each
the present node or state. using the binary tree is,
21
Disadvantages 1 0
1. They are very expensive for complex problems. 18
13
{0} The Huffman codes are,
1, 4, 6, 7, 13
2. They are prone to errors in the classification 1 0
} } }

5, 6, 7, 13 7 1 → {1111}
problems with more classes. 11 {10}
11, 7, 13 1 0 4 → {1110}
3. Huffman Coding 6
18, 13 5 6 → {110}
{110}
Huffman coding is the one of the best and
}

21 1 0 7 → {10}
important applications of binary tree in communication. 1 4
{111} {1110} 13 → {0}
For example, consider the transmission of text. Firstly, the
message should be encrypted by using 0s and 1s i.e., each 4. Game Trees
of the alphabet should be represented with 0s and 1s binary
Game trees is the most exciting application of
code sequentially. The code given to an alphabet should be
binary tree in games such as chess, nim, go, checkers,
unique and each alphabet should be assigned with a code
tic-tac-toe and so on. The game is explained by using
of length 5 as 24 < 26 < 25. Then the transmitted message
the tic-tac-toe game.
at receiver end is decrypted into alphabets and then the
message is recognized by the receiver. The message may Tic-tac-toe game is a 2 player game it starts with
consists of n number of letters, from which some letters the empty board and each of the player is assigned with
may appear many number of times while other not appear a symbol like ‘X’ and ‘O’. Each player finds the best
frequently. So, the most frequently occurred letters are move to win the game. The win value is used in the
represented with short frequencies and the less frequently implementation and it is calculated as the difference
occurred letters are represented with long frequencies.
between the number of rows, columns and diagonals
Consider a message of 500 letters that is to be that are left open for one player and other left for the
transmitted. The total number of bits to be sent will
second player. The function, say computewinvalue ( ) is
be 500 × 5. Among these 500 letters, the (assume that
used to compute and returns the winvalue. It is possible
each letter repeated for 50 times) letters a, e, s, u, i are
appeared maximum number of times and x, w appeared to form a tree using the possible moves from the current
minimum number of times. Make the most frequently position. This is called as ‘game tree’. For a player the
occurred letters with the size of 2. Then the length of the move with the highest-win-value will be the best move.
message will be reduced by a factor. This type of coding Now, consider a position and the five possible moves
is called as variable length coding. from that position with their winvalues.

137 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
X O
X
O

X O XOX X O X O XO
XX X X X X X
O O X O XO O
2 2 2 2 1
Figure: Game Tree and Winvlues of Each Possible Move From a Position
The winvalues for each possible move were calculated. The four possible moves have the same winvalue.
The move in the fourth position will lead to win for ‘X’ and other moves leads to the victory of ‘O’. It says that the
move with a small win value is better than the move with highest win value.
The computewinvlue( ) function is not enough to expect the result of the game it needs to revise this
function. The best and efficient way to play the game is to look a head for different possible moves from the current
position and significantly to get a better move. Let lookahead be the number of moves from a position. It is possible
to form a tree using all the possible moves from the current position.
X
1

–X – –
X
X 1
–1
–2

+ + + + + + + +
+ + + X X X X
OX X X X X O O XO X
O O X X X O
O O O O O

–1 –1 0 0 –2 1 2 1 0 0 1 1
Figure: Game tree for tic-tac-toe Game
The game tree for a tic-tac-toe game is mentioned in above diagram. Here the ‘+’ symbol denotes the player
who started the game first and ‘–’ symbol denotes the opponent player. The computation for the best move starts
from the root node with ‘+’ symbol and the remaining are assigned with ‘+’ or ‘–’ depending on the computation.
Q39. Write the algorithm for the construction of Expression Tree. Explain the steps to construct
an expression tree for the expression E = (a + b × c)/d.
Answer : Nov./Dec.-18, Q11(a) [OU]
Algorithm for the Construction of Expression Tree
Don’t Think
An algorithm to construct expression tree is as follows. I am Complex
1. Start.
2. Get a token from E.
3. Create a node pr for the token.
4. If (symbol is operand) then
push the node pr onto the stack.
5. Else if (symbol is operator) then
5.1 rp = pop( ) [∴ lp and rp are the pointers to left and right subtrees respectively]
lp = pop( )
5.2 Add lp, rp to left and right of pr respectively.
5.3 Make a tree, whose root is the operator, and lp, rp are left and right children, respectively.
5.4 Push node pr that is attached to left and right subtrees of the stack.
6. Repeat the steps 1-5 till the expression ends.
7. Pop the pointer pr, which points to the root node.
8. Stop.

Publishers and Distributors Pvt. Ltd. 138


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Steps to Construct an Expression Tree Step 5
Given Expression, E = (a + b × c)/d Next, the operator ‘/’ is encountered, so the two
The postfix expression for the given expression pointers in the stack are popped and a tree is formed.
E is, abc × + d/ Here ‘/’ is the new root and the popped pointers are its
Step 1 children. This can be shown in figure (5).
Initially, the operands a, b, c are pushed into the
stack one after the other. It forms one node tree in the
stack for each operand i.e., (a, b, c) along with pointers
for each of them. This can be shown in figure (1). abc × + d /
/
Stack + d
c
a ×
abc × + d / b
a b c
Stack
Figure (5)
Figure (1)
Step 6
Step 2 After the completion of input processing, the
Next, the operator ‘×’ is encountered, so the stack is popped and the pointer pointing to expression
two topmost pointers are popped and a tree is formed, tree’s root node is returned.
wherein ‘×’ is root and a, b are its children. A pointer is
assigned to the root ‘×’ in the stack. This can be shown 3.2 Graphs
in the figure (2).
3.2.1 Introduction
Q40. Define graph. Give the basic terminologies
× of graphs.
abc × + d / b c
Answer :
a
Stack Graph
Figure (2) A graph can be defined as
Step 3 G = (V, E) where,
I am complex but Worthy
Next, the operator ‘+’ is encountered, so the (i) V is the set of elements
two topmost pointers are popped and a tree is formed, called nodes or vertices or points.
wherein ‘+’ is the new root and the popped pointers are (ii) E is the set of edges of the graph identified with
its children. This can be shown in the figure (3). a unique pair (U, V ) of nodes.
Here (U, V) pair denotes that, there is an edge
from node U to node V.
abc × + d / Terminologies of Graphs
+ 1. Directed Graph
Stack a ×
A graph in which every edge is directed known
b c as a directed graph.
Figure (3) Example
Step 4 B
Next, the operand d is pushed into the stack, along
with a pointer to form one node tree within the stack. A C
This can be shown in figure (4).
D

d Figure: Directed Graph


abc × + d / Here, the directed edge is shown by means of
+
arrows which also shows the direction.
Stack a ×
2. Weighted Graph
b c If the edges in a graph is labeled with weights
Figure (4) then it is called as weighted graph.

139 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
3. Adjacent Vertices
3.2.2 Graph Abstract Data Type
Let x be an edge between two pair of vertices (U,
V ) in an undirected graph. Then, the nodes U and V are Q41. Explain in detail about graph ADT.
said to be adjacent to each other.
Answer :
Let x be an edge between an ordered pair of
vertices (U, V ). That is, the edge is originating at U and Graph ADT
terminating at V. Then U is said to be adjacent to V and A graph is a data structure that consists of set
V is said to be adjacent to U. of nodes (vertices) and set of arcs (edges). Every edge
4. Parallel Edges present in the graph is indicated by a pair of vertices.
If a pair of vertices contains more than one edge The various graph ADT operations or methods
then the edges are called as parallel edges. The graph are as follows,
will be called as multigraph in such cases. 1. create( )
5. Complete Graph 2. insert vertex( )
If a vertex contains edges to all the vertices from
3. delete vertex( )
it, then the graph is called complete graph.
4. insert edge( )
6. Acyclic Graph
If there is a path that contains edges starting from 5. delete edge( )
a vertex and ending at the same vertex, then the path is 6. boolean isEmpty( )
called as cycle. The graph will be called as cyclic graph.
7. list adjacent( ).
If a graph does not contain any cycles, then such graph
will be called as acyclic graph. 1. create( )
7. Connected Graphs This method is used to create an empty graph.
A graph is said to be connected, if there exists a The created graph does not contain any vertices
path between any two vertices U and V. Otherwise, the and edges.
graph is disconnected.
2. insert Vertex (graph, ver1)
Example (i)
This method is used to insert a new vertex ver1
A B into the graph. The inserted vertex does not
contain any adjacent edges.
3. delete Vertex (graph, ver1)
This method is used to delete an existing vertex
C D
ver1 from the graph. All the adjacent edges that
Figure: Connected Graph are connected with vertex ver1 are also being
deleted.
The graph shown above is connected graph
because there is a path from each vertex. 4. insert Edge (graph, ver2, ver3)
path A to B: A → B This method inserts an edge e1 between the
A to C: A → B → D → C vertices ver2 and ver3.
A to D: A → B → D 5. delete Edge(graph, ver2, ver3)
Similarly, every node has a path to other node This method deletes an edge e1 existing between
which can be verified from the graph. the vertices ver2 and ver3.
Example (ii) 6. boolean isEmpty(graph)
A B This method checks whether the graph is empty
or not then if empty then returns true. Otherwise
returns false.
7. list Adjacent (graph, v)
C D
This method returns all the respective edges that
are adjacent to the vertex ver1.
Figure: Disconnected Graph
The graph shown is disconnected because there The code snippet for implementing graph ADT
is no path from A to D, and from B to any other node is as follows,
and so on. class GraphADT

Publishers and Distributors Pvt. Ltd. 140


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
{ (ii) Delete Vertex
public: To delete a vertex, initially search for the vertex
and then delete the element. After finding the vertex check
virtual ~GraphADT( )
whether any arc is entering (indegree) or leaving (outde-
{ gree) the vertex. A vertex with degree greater than zero
} cannot be deleted. So to handle such a vertex, a check for
indegree and outdegree in the vertex is required.
bool IsEmpty( ) Const {return vertices = 0};
Example
Int NumberOfVertices( ) Const {return vertices};
A B A B
int NumberOfEdges( ) Const {return edge} Delete
Vertex
virtual int Degree (int p) Const = 0;
D
virtual bool ExistEdge (int p, int q) Const = 0;
C D C
virtual void InsertVertex (int q) = 0;
Before After
virtual void InsertEdge (int p, int q) = 0; deletion deletion
virtual void DeleteVertex (int q) = 0; (iii) Insert Edge
virtual void DeleteEdge (int p, int q) = 0; Add edge operation connects a vertex to a destina-
private: tion vertex. It is necessary to specify two vertices inorder
to add an edge. For a diagraph, one vertex as the source
int vertices; vertex and the other vertex as the destination vertex must
int edges; be specified. For multiple edges from a single vertex,
}; invoke this operation only once with all the adjacent
vertices.
Q42. Write Graph ADT. Explain the following
Example
operations on a graph with examples.
A B A B
(i) Insert Vertex
(ii) Delete Vertex Insert Edge
(E, D)
(iii) Insert Edge
(iv) Delete Edge. C D C D

Answer : June/July-19, Q11(b) [OU]

Graph ADT
For answer refer Unit-III, Page No. 140, Q.No. E E
41, Topic: Graph ADT (First Paragraph Only).
Before Insertion After Insertion
(i) Insert Vertex
In the above example, edge {E, D} is inserted.
To insert a vertex into the graph, first allocate the
(iv) Delete Edge
memory to the new vertex and then store the input data
in the new vertex. Next, set all the meta data elements Delete edge operation removes an edge from a
to NULL. While inserting the vertex check whether the graph. For edge deletion the source vertex must be located
graph is empty or the new vertex must be inserted before in the vertex list and the destination vertex must be located
the first vertex. In both the cases the new vertex becomes in the adjacency list of the source vertex. Edge is located
the first node of the graph. If neither of the case is true after determining the source and destination vertices and
then insert the new vertex in sequence. is therefore removed. The degree of source and destination
vertices are adjusted and the memory is recycled.
Example
Example
A B A B
Insert
Vertex

E
C D C D
Before
insertion

After
E
insertion In the above graph, edge {C, D} is removed.

141 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
The adjacency matrix for the graph given in
3.2.3 Representation of Graphs example 2,
Q43. Explain the representation of graphs us- 1 2 3 4
ing the adjacency matrix, adjacency list
1 0 1 10 01
and adjacency multi-list.
A=2 01 0 0 1
Answer : (Model Paper-II, Q18(b) | Nov./Dec.-18, Q11(b) [OU])
3 1 0 0 1
The representation of graphs are 4 01 01 1 0
as follows,
(a) Adjacency Matrix Hey! 0 1 0 0 0 1 0 0
Don’t
An adjacency matrix A = (aij) of escape 0 0 0 1 0 0 0 1
graph G is defined as, from A2 = AA =
me 1 0 0 1 1 0 0 1
1 if Vi is adjacent to V j
aij  0 0 1 0 0 0 1 0
0 otherwise
In case of directed graph, “Vi is adjacent to Vj” 1 2 3 4
means that there is a directed edge from Vi to Vj. 1 0 0 0 1
Example 1 2 0 0 1 0
A2 =
Consider the undirected graph given below, 3 0 1 1 0
1 2 4 1 0 0 1
A2 indicates that there is one path of length 2 from
V1 to V4, V2 to V3, V3 to V2, V3 to V3, V4 to V1 and V4 to V4
which can be verified from graph of example 2.
3 4
. In general, AK represents an adjacency matrix
showing the number of paths of length k present between
Adjacency matrix is,
two pair of vertices.
1 2 3 4
Drawback of Adjacency Matrix Representation
1 0 1 1 1
To represent a graph of n nodes, adjacency matrix
A= 2 1 0 0 1 of size n × n is required. For most of the graphs, only few
3 1 0 0 1 entries will be filled in matrix. So, it leads to memory
4 1 1 1 0 wastage.

Example 2 Example

Consider the directed graph shown below, 1 2

1 2

4 3

Adjacency matrix for this graph is,


1 2 3 4
3 4
1 0 1 0 0
2 0 0 1 0
Here aij has 1 when there is an edge from Vi to Vj. 3 0 0 0 0
The adjacency matrix A shows the number of 4 1 0 1 0
paths of length 1 between any pair of vertices (Vi, Vj). Here, the size of matrix is 4 × 4 = 16, but only
The adjacency matrix A2 shows the number of paths of 4 entries are filled with 1. Hence, a lot of memory is
length 2 between any pair of vertices. wasted.

Publishers and Distributors Pvt. Ltd. 142


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
(b) Adjacency List (c) Adjacency Multilists
In adjacency list representation of a graph, Adjacency multilists are the lists in which nodes
G = (V, E), each vertex of a graph is represented by may be shared among multiple lists. In adjacency
an adjacency list. The adjacency list corresponding to multilists, for every edge there is exactly one node. This
vertex ‘i’ contains all vertices that are adjacent to ‘i’ in node is present on the adjacency lists for the two nodes
‘G’. In adjacency list representation, each adjacency list incident upon it. Consider the following graph,
is maintained as a chain so it is called linked adjacency N1 b
list representation. a

In this representation, an array ‘A’ is used such N2


N5
that A[i] points to the linked list that includes all vertices
to which a particular vertex (Vi) is connected. Each node c d
in the linked list contains two components i.e., vertex
and link. N4 N3
e
The following figures illustrates linked adjacency
list representations for directed and undirected graphs. The adjacency multilists for this graph are as
V1 follows,

a a b N5 N2 N1 Vertices

Node a : N1 → N5
V2 V5 V3 b b d Null N3 Node b : N1 → N2
N2
Node c : N4 → N5
c d e Null N4 N3 Node d : N2 → N3
V4 Node e : N3 → N4

Figure: Undirected Graph (G1) d c e N5 Null N4


[V1 ] V2 V3 V5 NULL

[V2 ] V1 V4 V5 NULL e c a Null Null N5

[V3 ] V1 V4 V5 NULL
The format of node structure in adjacency
[V4 ] V2 V3 V5 NULL multilists is
[V5 ] V1 V2 V3 V4 NULL Node 1 Node 2 Link 1 Link 2
Figure: Adjacency List Representation for Graph (G1) Where Node1 and Node2 represents the shared
V1 edge. Link 1 and link 2 represents the next unvisited
edges from Node 1 and Node 2. For example, nodes for
shared edge N1 are a and b. The next unvisited edges
V2 V3
for those nodes are N5 and N2.
3.2.4 Graph Traversal – Depth-first
V4 V5 Search, Breadth-first Search

Figure: Directed Graph (G2) Q44. Briefly describe about the graph traversal
techniques. For the following graph, give
[V1 ] V2 V3 NULL the result of DFS and BSF traversals.
(Model Paper-II, Q17 | May/June-18, Q11(b) [OU])
[V2 ] V4 V5 NULL
7
3
[V3 ] V1 V5 NULL 6

1 8
[V4 ] V5 NULL
5

2
[V5 ] NULL 4

Figure: Adjacency List Representation for Graph (G2) OR


143 Publishers and Distributors Pvt. Ltd.
Computer Science Paper-III Data Structures Using C++
Explain Depth-First-Search (DFS) method Let node 1 be the starting node
for Graphs. May/June-19, Q7(b) [MGU]
1. State[1] = 1
(Refer Only Topic: Depth First Search Traversal) State[2] = 1
OR State[3] = 1
Explain Breadth-First-Search (BSF) State[4] = 1
method for Graphs.
State[5] = 1
(Refer Only Topic: Breadth First Search Traversal)
State[6] = 1
Answer : Nov./Dec.-18, Q7(b) [MGU]
State[7] = 1
Various types of graph traversal methods are as
follows, State[8] = 1

(i) Depth First Search Traversal 2. Begin with node 1. Push it onto stack.
In this method, traversal is started
from a given vertex V in the graph. This
1
vertex is marked as visited and any of the
I am a
Repeated
Question

unvisited vertex adjacent to V is visited. 3. While stack ≠ empty


Then neighbour of V is visited. This
(i) Pop 1
process is continued until no new node
can be visited. Now this is backtracked to visit unvisited State[1] = 3 [1 is visited]
vertices if any left. Stack is used to keep track of all nodes (ii) Push nodes adjacent to 1 onto stack and
adjacent to a vertex.
make their State waiting.
Algorithm: Depth-First(V)
State[3] = 2
1. Initialize all the nodes to ready state and stack to
empty State[2] = 2

state[v] = 1 [ 1 indicates Ready state]


2. Begin with any arbitrary node ‘s’ in graph, push 3
it onto stack and change its state to waiting 2
state[s] = 2 [ 2 indicates waiting state]
4. (i) Pop 3
3. Repeat through step 5 while stack is not empty
4. Pop node N of stack and mark the status of node State[3] = 3 [3 is visited]
to be visited (ii) Push nodes adjacent to 3 in stack
state[N] = 3 [ 3 indicates visited] State[7] = 2
5. Push all nodes w adjacent to N into stack and State[6] = 2
mark their status as waiting
state[w] = 2
6. If the graph still contains nodes which are in ready 7
state goto step 2. 6
7. Return. 2
Example
5. (i) Pop 7
Given graph is,
State[7] = 3 [7 is visited]
7 (ii) Push nodes adjacent to 7 in stack
3
State[8] = 2
6

1 8
8
5
6
2
4 2

Publishers and Distributors Pvt. Ltd. 144


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
6. (i) Pop 8 (ii) Breadth First Search Traversal
State[8] = 3 [8 is visited] In this method, traversal is started from given
(ii) Push nodes adjacent to 8 vertex V and all the nodes adjacent to V from left to right
State[5] = 2 are visited. Data structure queue is used to keep track of
all the adjacent nodes. The first node visited is the first
State[4] = 2
node whose successors are visited.

5
Algorithm: Breadth-First [V]
4 1. Initialize all nodes to ready state.
6 state[V] = 1 [Here, V represents all nodes
2 of graph].
7. (i) Pop 5 2. Place starting node ‘S’ in queue and change its
State[5] = 3 [5 is visited] state to waiting.
(ii) Nodes adjacent to 5 is 2 which is already state[S] = 2
present in the stack.
3. Repeat through step 5 until queue is not empty.
4. Remove a node N from queue and change its
4
status to visited.
6
state[N] = 3
2
5. Add to queue, all neighbours W of ‘N’ which are
8. (i) Pop 4
in ready state and change their status to waiting
State[4] = 3 [4 is visited] state.
(ii) Nodes adjacent to 4 is 2 that is already
state[W] = 2
present in the stack.
6. Return.
Example
6
Given graph is,
2
7
9. (i) Pop 6
3
State[6] = 3 [6 is visited]
6
(ii) Nodes adjacent to 6 are 3 and 8 that are
1 8
already visited.
5

2
2 4

10. (i) Pop 2 1. State[1] = 1


State[2] = 3 [2 is visited]
Push it in to queue.
(ii) Nodes adjacent to 2 are 4 and 5 which are
already visited. 1
Now, the stack is empty.
2. While queue is not empty,
The order of visiting the nodes is,
1 3 7 8 5 4 6 2 (i) Remove 1,
The spanning tree obtained using dfs is given below, State[1] = 3[1 is visited]
7 (ii) Insert nodes adjacent to 1 i.e., 2 and 3 to
3 queue.
1
8 2 3
5

2
State[3] = 2
6 4
State[2] = 2
145 Publishers and Distributors Pvt. Ltd.
Computer Science Paper-III Data Structures Using C++
3. (i) Remove 2,
3.2.5 Spanning Tree – Prim’s Algorithm,
State[2] = 3[2 is visited] Kruskal’s Algorithm
(ii) Insert nodes adjacent to 2 i.e., 4 and 5 to queue. Q45. What is spanning tree and minimum
3 4 5 spanning tree? Construct minimum
s p a n n i n g t r e e u s i n g K r u s k a l ’s
State[5] = 2 algorithm.
State[4] = 2 a 20 b 30 c 10 d
4. (i) Remove 3, 30 10 30 50
State[3] = 3 [3 is visited] e 40 f 30 g 30 h
(ii) Insert nodes adjacent to 3 i.e 6, 7 to queue. 40 20 10 30
i 30 j 30 k 10 l
4 5 6 8

State[6] = 2 Answer : (Model Paper-III, Q17(a) | Nov./Dec.-19, Q11(b) [OU])

State[7] = 2 Spanning Tree


5. (i) Remove 4, A spanning tree for a connected,
State[4] = 3 [4 is visited] undirected graph, G = (V, E) is a
subgraph of G that is an undirected Remember me
(ii) Insert nodes adjacent to 4 i.e., 8
tree and contains all the vertices of with concept
5 6 7 8 G. It can also be defined as “A sub
graph T = (V, E) is a spanning tree of G if T is a tree. A
State[8] = 2 spanning tree of a graph should include all the vertices
6. (i) Remove 5, and a subset of edges (E)”.
State[5] = 3 [5 is visited] Example
6 7 8 Consider a connected undirected graph shown in
figure (1),
(ii) No nodes are adjacent to 5 in ready state.
7. (i) Remove 6,
State[6] = 3 [6 is visited]
7 8

(ii) No nodes are adjacent to 6 in ready state


8. (i) Remove 7,
State[7] = 3 [7 is visited] Figure (1): A Graph
The figure (2) shows some of the spanning trees
8
of figure (1).
(ii) No nodes are adjacent to 8 in ready state.
9. (i) Remove 8
State[8] = 0 [3 is visited]
(ii) No nodes are adjacent to 8 in ready state.
∴ The queue is empty.
The order in which the nodes are visited is,
(a) (b)
1 2 3 4 5 6 7 8
7

3
6 8

1
5
2

4
(c) (d)

Publishers and Distributors Pvt. Ltd. 146


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Step-4
1
a 20 b 30 c 10 d
2 3 30 10 30 50
e 40 f 30 g 30 h
40 20 10 30
4 j 30 k
i 30 10 l
(e) (f) Figure: Choose e4 = kl
Figure (2): Some Spanning Trees of Figure (1)
Step-5
Minimum Spanning Tree
a 20 b 30 c 10 d
A minimum spanning tree is a spanning tree, that
30 10 30 50
has weights with the edges and the total weight of the e 40 f 30 g 30 h
tree (the sum of the weights of its edges) as minimum.
40 20 10 30
Prim’s and Kruskal’s algorithms are used to find mini- i 30 j 30 k 10 l
mum spanning tree.
Example Figure: Choose e5 = ab

Given that, Step-6


a 20 b 30 c 10 d a 20 b 30 c 10 d
30 10 30 50 30 10 30 50
e 40 f 30 g 30 h e 40 f 30 g 30 h
40 20 10 30 40 20 10 30
i 30 j 30 k 10 l i 30 j 30 k 10 l

The following are the various steps involved in Figure: Choose e6 = fj


Kruskal’s algorithm to find minimum spanning tree.
Step-7
Step-1
a 20 b 30 c 10 d
a 20 b 30 c 10 d
30 10 30 50
30 10 30 50 e 40 f 30 g 30 h
e 40 f 30 g 30 h 40 20 10 30
40 20 i 30 j 30 k 10 l
10 30
i 30 j 30 k 10 l
Figure: Choose e7 = ae
Figure: Choose e1 = bf
Step-8
Step-2
a 20 b 30 c 10 d
a 20 b 30 c 10 d
30 10 30 50
30 10 30 50 e 40 f 30 g 30 h
e 40 f 30 g 30 h
40 20 10 30
40 20 10 30 i 30 j 30 k 10 l
i 30 j 30 k 10 l

Figure: Choose e2 = cd Figure: Choose e8 = bc

Step-3 Step-9
a 20 b 30 c 10 d a 20 b 30 c 10 d
30 10 30 50 30 10 30 50
e 40 f 30 g 30 h e 40 f 30 g 30 h
40 20 10 30 40 20 10 30
i 30 j 30 k 10 l i 30 j 30 k 10 l
Figure: Choose e3 = gk Figure: Choose e9 = cg

147 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Step-10 Algorithm Prim(G)
a 20 b 30 c 10 d //Input: A weighted connected graph G = (V, E)
30 10 30 50 //Output: T, the minimum spanning tree of G
e 40 f 30 g 30 h (Here, fg is ignored
{
40 20 10 30 because, it forms a
i 30 j 30 k 10 l V = {V0}
cycle)
T = { } //empty graph
Figure: Choose e10 = gh
for i = 1 to n – 2
Step-11
a {
20 b 30 c 10 d
choose a nearest neighbour Ci of V that
30 10 30 50
e 40 f 30 g 30 h is adjacent to Vj, Vj ∈ V and for which
40 20 10 30 the edge eij = (Vi,Vj) does not form a
i 30 j 30 k 10 l cycle with members of T.
Figure: Choose e11 = ij V:= V {Vi} //add Vi to V
According to Step-1 of Kruskal’s algorithm, it T:= T {eij} //and add (Vi, Vj) to T
choose e1 = bf as it has the minimum weight. Then imple- }
ment step 2 of Kruskal’s algorithm by recursively selecting
return T;
the next edge having the least weight until |E| = n – 1.
}
So, the minimum spanning tree is,
a
Example
20 b 30 c 10 d
Consider a connected weighted graph ‘G’,
30 10 30 50
e 40 f 30 g 30 h
40 20 10 30
i 30 j 30 k 10 l
Figure: Minimum Spanning Tree
Q46. Explain the minimum cost spanning tree
algorithms.
Answer :
Minimum cost spanning tree is a spanning tree
with the minimum cost (i.e., sum of the cost on its edges).
The two efficient algorithms used for constructing
minimum cost spanning trees are,
1. Prim’s algorithm
2. Kruskal’s algorithm.
1. Prim’s Algorithm Figure (1): Connected Weighted Graph G
For answer refer Unit-III, Page No. 148, Q.No. 47.
Step 1
2. Kruskal’s Algorithm
Start with the first vertex i.e., V1. The edge weights
For answer refer Unit-III, Page No. 150, Q.No. 49.
of this vertex are compared i.e., 1 is compared with 3.
Q47. Explain the procedure for finding minimum Since, 1 is smaller than 3, the edge{V1, V2} is selected.
cost of the graph using Prim’s algorithm.
OR
Explain Prim’s algorithms for spanning tree.
Answer : May/June-19, Q7(a) [MGU]

Prim’s Algorithm
Prim’s algorithm generates minimal spanning tree
Figure (2)
by selecting smallest weight edges. Initially, it selects an
edge with smallest weight and puts it into the spanning Step 2
tree. Then successive edges adjacent to the initial edge Now, consider the vertex V2. The edge weights of
with minimum weight are added to the tree. However, this vertex are compared and the edge with the smallest
these edges must be selected such that, they do not form weight is selected i.e., edge {V2, V3}with weight 2 is
a circuit. The algorithm for this method is as follows, selected.

Publishers and Distributors Pvt. Ltd. 148


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Step 5
The edge weight of V6 are compared and the edge
{V5, V6} with weight 3 is selected.

Figure (3)
Step 3
The edge weights of V3 are compared and the edge {V3,
V4} is selected, since it has the smallest weight (i.e., 2).

Figure (6)
The resulting graph obtained is a minimum
spanning tree in which the comparisons made by the tree
algorithm are totally 5, [for n = 6 vertices, (n −1) i.e., (6
−1)] comparisons are performed. Hence, if the input is
a complete undirected graph with n vertices and vi is the
start vertex then (n −1) comparisons of edge weights will
be performed by the minimum spanning tree algorithm.
Q48. Prove that the prism’s algorithm finds a
minimum spanning tree.
Answer :
Correctness of Prim’s Algorithm
Theorem
Prim’s algorithm finds a minimal spanning tree.
Figure (4)
Proof
Step 4
To prove the correctness of prim’s algorithm, the
The edge weights of V4 are compared and the edge correctness of basis and inductive steps has to be proved.
{V4 , V5} with weight 4 is selected even though edge {V4 , V1} Basis Step
has the smallest value (i.e., 1). This is because, if the Initially, the tree has no edges. Hence, the basis
{V4 , V1} is selected, then the graph form a cycle, which is not step is true.
allowed in a spanning tree.
Induction Step
Induction is used to show that, the tree constructed
after each iteration is a minimal spanning tree. Eventually
at the end of prim’s algorithm, the constructed tree is a
minimal spanning tree.
Assume that, the original tree (T) constructed
by the prim’s algorithm is a minimal spanning tree.
Also assume (x, y) as the next edge selected by prim’s
algorithm such that the vertex “x” is in the original tree
(T) and the vertex “y” is not in ‘T’. Let there be another
new tree (T’) containing all the vertices of ‘T’, in addi-
tion to those that are not in the original tree. Hence, the
new tree (T’) becomes a part of the original tree (T).
The minimum weight edge (x, y) has one vertex in the
new tree and another in the original tree. If this edge is
inserted into the new tree, the graph that is formed will
also be a minimal spanning tree. Hence, the inductive
Figure (5) step is also proved.
149 Publishers and Distributors Pvt. Ltd.
Computer Science Paper-III Data Structures Using C++
Q49. Discuss about Kruskal algorithm. The following are the steps involved in Kruskal’s
May-18, Q7(b) [MGU] algorithm to find the minimum spanning tree.
OR Step-1
Explain Kruskal’s algorithms for spanning
tree.
Answer : (Modep Paper-III, Q17(b) | Nov./Dec.-18, Q7(a) [MGU])

Kruskal’s Algorithm
Kruskal’s algorithm
selects an edge that have
minimum weight in the graph.

ple
Then, add the edges individually

Very Sim
ex
pl
m

that has minimum weight in such


Co

t
Figure (2): Choose e1 = BC
ng

bu
i

a way that, it does not form a


ok
Lo

simple circuit with those edges Step-2


which has selected. This process is stopped when the
(n – 1) edges have been selected.
Algorithm Kruskal(G)
//Input : A weighted connected graph G = (V, E)
//Output : T, the minimum spanning tree of G
{
Sort E in increasing order by weight
T : ={ } //empty graph
for i = 1 to n – 1 Figure (3): Choose e2 = FE
{
Step-3
e : = any edge in G with smallest
weight that does not form a
simple circuit when added to T.
T=T {e} //add e to T
}
return T;
}
Example
Consider a weighted connected graph as shown
in figure (1). Figure (4): Choose e3 = GB

Step-4

Figure (1): Graph ‘G’ Figure (5): Choose e4 = AG

Publishers and Distributors Pvt. Ltd. 150


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Step-5 Basis Step
Initially, the subgraph that has no edges is a
minimal spanning tree. Hence, the correctness of basis
step is proved.
Induction Step
The initial phase in this step shows that, the sub-
graph that is constructed at the result of each iteration is
a minimal spanning tree. Eventually, the subgraph that
is constructed at the end after following all the iterations
is also a minimal spanning tree.
Figure (6): Choose e5 = ED
Let there be two subgraphs an original subgraph
and a new subgraph constructed by the Kruskal’s algo-
Step-6
rithm. Assume that the original subgraph is in a minimal
spanning tree. Also assume that (x, y) is the next edge
selected by Kruskal’s algorithm such that, one vertex is in
the original subgraph and the others are not. If this edge
i.e., (x, y) which is assumed to have minimum weight
edge, is inserted into the original subgraph, then the
resulting graph will be a minimal spanning tree. Hence,
the correctness of inductive step is also proved.
Q51. Differentiate between Prim’s and Krus-
kal’s algorithm.
Figure (7): Choose e6 = GF Answer :
According to step 1 of Kruskal’s algorithm, It
Prim’s Kruskal’s
choose e1 = BC as it has the minimum weight. Then
Algorithm Algorithm
implement step 2 of Kruskal’s algorithm by recursively
1. It starts with a 1. It starts with each
selecting the next edge having the least weight until |E|
single vertex of a and every vertex of
= n – 1.
graph similar to the graph and adds the
So, the minimum spanning tree is, tree and gradually smallest edge that joins
adds the smallest the two trees as the
edge to make the whole.
tree to grow by one
more vertex.
2. It is suitable when 2. It is suitable when all
only a single tree the edges and vertices
and only a few are simultaneously tak-
edges are taken en into consideration.
into consideration
Figure (8): A Minimum Spanning Tree at a time.
Q50. Prove that Kruskal’s algorithm generates 3. It is considered as 3. It is more space con-
a minimum cost spanning tree. more space-effi- suming.
cient since only
Answer : one tree is taken
Correctness of Kruskal’s Algorithm and the edges that
Theorem connect to the ver-
tices in the tree are
Kruskal’s algorithm finds a minimal spanning examined.
tree.
4. It is more time- 4. It is considered as time-
Proof consuming. efficient because order-
To prove the correctness of Kruskal’s algorithm, ing of edges as per their
the correctness of basis and inductive steps has to be weights is possible for
proved. traversing them quickly.

151 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Q52. Discuss in brief about the following, There are many biconnected components for this
(i) Connected components biconnected graph. Following are some of them,
(ii) Biconnected components.
Answer :
(i) Connected Components (i)
The connected components of a graph can be
defined as a set of nodes that are connected in pairs with
the help of edges. The node pairs are connected only if
they belong to same component.
Example

(ii)

Figure: Graph
The connected components of the above graph are,
(iii)

(iv)

Figure: Connected Component Using BFS


Q53. Define the terms graph, tree, spanning
tree, and minimum spanning tree. Con-
struct a minimum spanning tree (step-
by-step) from the following graph using
prim’s algorithm.
12
A B

17 1
3
Figure: Connected Component Using DFS
15 F C
2
(ii) Biconnected Components
19 10
A connected graph is biconnected if the removal
5
of any single vertex (and all edges incident on that vertex) E D
14
cannot disconnect the graph. It contains a common vertex
for two biconnected components of similar graph. It infers Answer : Nov./Dec.-17, Q11(b) [OU]
that, an edge cannot be common to multiple biconnected Graph
components. Consider the following biconnected graph. For answer refer Unit-III, Page No. 139, Q.No. 40,
Topic: Graph.
Tree
For answer refer Unit-III, Page No. 117, Q.No. 21,
Topic: Tree.
Spanning Tree
For answer refer Unit-III, Page No. 146, Q.No. 45,
Topic: Spanning Tree.
Minimum Spanning Tree
For answer refer Unit-III, Page No. 147, Q.No. 45,
Figure Topic: Minimum Spanning Tree.

Publishers and Distributors Pvt. Ltd. 152


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
Problem
Given graph is,
3.3 Hashing
12
A B 3.3.1 Introduction, Hash Functions
17 1
3
Q54. Explain in detail about the basic concepts
15 F C
of hashing.
2
19 10 Answer : (Model Paper-III, Q18(a) | Nov./Dec.-19, Q9(b) [MGU])
5 The main aim of hashed search is to search the
E
14
D data with the help of only a single test. The concept of
Step 1 hashing is nothing but a key-to-address mapping process.
Key
Start with the first vertex i.e., A. The edge weights
of this vertex are compared i.e., 12 is compared with 15.
Since 12 is smaller than 15 the edge {A, B} is selected. Hash Functions
(HF)
12 Remember me
A B with concept

Step 2 Address
Now, consider the vertex B. The edge weights of this Figure: Hashing
vertex are compared and the edge with the smallest weight In other words, hashing can be defined as a
is selected i.e., edge {B, C} with weight 1 is selected. transformation of key to address wherein keys are
12 mapped to their associated addresses present in the list.
A B
1
This mapping transformation can be as shown below,
Key {103003 104090 224854
C
Step 3 Hash Function (HF)
Address { 2 6 3
The edge weights of C are compared and the
edge {C, D} is selected with the weight 5 even though
the edge {C, B} has smallest weight i.e., 1.
12
A B [000] [001] [002] [003] [004] [005] [006] [007] [008] [009] [050]
1
000 001 002 003 006 050
C
Rani
5 Smith
D John Ravi

Step 4
The edge weights of D are compared and the edge Figure: Concept of Hashing
{D, F} with weight 10 is selected even thought the edge In the above figure, the three different keys hashes
{D, B} has smallest weight i.e., 2. to three different addresses present inside the list/array.
12 This process of the allotment of the key to a particular
A B
1 address is done by the hashing algorithm. It produces
F C an address called as the home address and a set of such
10
address in the memory is called the prime area.
D 5
Sometimes it happens that the keys collide at a
Step 5 certain address called as collision. In order to overcome
The edge weight of F are compared and the edge this, one of keys and its related data should be placed
{F, E} with weight 19 is selected even though the edge in another address. This is called collision resolution. It
can be shown as follows,
{F, B} has smallest weight i.e., 3. x, y collide
12 y, z collide
A B
1
collision resolution
F 10 C z x y
E 19 D 5 [0] [4] [5] [9] [18]

The resulting graph obtained is a minimum span-


1. hash(x) collision
ning tree in which the comparisons made by the tree
2. hash(y) resolution
algorithm are totally 5, [for n = 6 vertices, (n – 1) i.e.,
3. hash(z)
(6 – 1)] comparisons are performed.

153 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Initially, ‘x’ key is hashed at address 9 using hash Example 2
(x). The ‘y’ key is also hashed to the same address. This Cluster of keys 2300, 2301, . . . . and 2113 then
results in a collision. It is resolved by placing key ‘y’ in these keys are mapped using the function (X mod
another location i.e., 18. Then again key ‘z’ is hashed to 35) which yields address as 7, 8, . . . . and 20.
the same location leading to a collision. To resolve this, There are many collisions in this cluster i.e., map-
its data is shifted and placed in another location i.e., ‘5’. ping two distinct elements into a single location
It is also important to use the same hashing as their remainder when divided by 35 yields the
algorithm for locating an element in the hashed list as same result.
the one used for insertion. For identifying the desired To overcome this collision we can use prime
element, first the key is hashed and its home address numbers which are large.
is determined. If the required element is present at that
2. Modulo-division Method
address, the search is completed. Otherwise, using
a collision resolution mechanism the next address is In this method of hashing, the key element is
determined and the search is continued until the element divided by the size of the array and the obtained
is found (or) knowing that it does not exist in the list. remainder is used for the address. So, the hash
This process is called as probing (or) probe. method is,
address = key % arraysize
Q55. Define hashing. Explain various hash
functions. Example
Answer : If key = 25 and arraysize = 12
Hashing Then the address = 25%12
Hashing is a technique that makes use of a hash \ address = 1
function for mapping pairs to the corresponding (entries) 3. Digit Extraction Method/Digit Analysis
positions in a hash table. Ideally a pair ‘P’ with a key A hashing function referred to as digit extraction
‘K’ is stored at a position f(K) by the hash function ‘f’. which forms addresses by selecting and shifting
Each hash table position can store one pair. digits or bits of the original key. In this method,
Hash Function some digits are selected and extracted from the
It is a function that is used to map the dictionary key which are used as address.
pairs to the corresponding entries in the hash table. Example
If the dictionary pair is ‘pair’ and if it consists of A key 7546123 is transformed to the address 2164
the key ‘key and if ‘f’ denotes the hash function then the by selecting digits in position 3 to 6 and reversing
pair “pair” is stored at f(key) position in a table. their order. For a given key set, some position in
In order to search a pair with the key K, initially the key and the same arrangement pattern should
find f(K) and determine whether a pair is at f(K) position be used consistently.
in the hash table. If it is not present at f(K) then we insert There are some other digit extraction methods
the pair at f(K) else if it occurs f(K) then find the desired other than the above. Like for example a key
pair that can be deleted if required. 1234567890 is transformed to the address 9542
Various Types of Hash Functions by selecting digits in position 2, 4, 5, and 9 and
Some of the desirable properties of a hashing function by reversing their order.
include speed and the generation of address uniformly. The
4. Folding Methods
following are some simple hashing functions.
In this method, the key is partitioned into its
1. Division Method
subparts which are joined or folded again to form
One of the first hashing function and the most
the address. The folding methods are of two types.
widely used concept which is defined as,
They are,
H(X) = (X mod m) + 1
(a) Fold shift method and
For some integer divisor m, the operation mod
denotes the modulus of X. In this item, X mod m (b) Fold boundary method.
refer to the modulus obtained after dividing X by m. (a) Fold Shift Method
Example 1 In this method of hashing, the key will be
X = 25, m = 12 partitioned into number of parts. The parts contain
H(25) = (25 % 12) + 1 the same size of digits. Later, the parts are added
=1+1=2 by ignoring the final carry to form the address.
So in the second location, value of X should be For instance, suppose a ‘9’ digit number
stored in hash table. 543951504 which is transformed into 3 digit
In mapping keys to address, there may be a chance numbers as 543, 951, 504. Later, they will get
to lose the uniformity by placing two different added to yield 1998. By ignoring the final carry
elements at the same location. ‘1’ resulting in 998. Hence, the address is 998.

Publishers and Distributors Pvt. Ltd. 154


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
(b)Fold Boundary Method
3.3.2 Collision Resolution Strategies
In this method of hashing, the outer most
partitions are reversed (i.e., folded). For instance, Q56. Discuss in detail various collision
the previous example gives three digits i.e., parts resolution techniques.
as 543, 951, 504. Now, it will be 345, 951, 405 Answer : Model Paper-III, Q18(b)
which is added to yield 1701. Hence, the result Collision Resolution
obtained is 701 by ignoring the final carry.
Collision occurred when a new key is hashed to an
5. Rotation Method
address by using the hashing methods that do not provide
In this method of hashing, the last character is moved one-to-one mapping. There is a need for handling these
to the front of the key. It is helpful in sequential collision. For this purpose, there are many methods that
allocation. For instance, a six-digit employee-ID is are independent of the hashing algorithm used.
800101 whose last character is rotated in the original
key. So, the rotated key is 180010. Types of Collision Resolution
6. MidSquare Method Various types of collision resolution are as
In this method of hashing, the key is multiplied follows,
by itself and address is obtained by solving the 1. Open addressing
middle digits from the number. The number of (i) Linear probing
digits selected usually depends on the table size. (ii) Quadratic probing
Example
(iii) Double hashing.
Consider a 4 digit key 5420, squaring this key
results 29376400. If ‘2’ digits address is required 2. Separate chaining (or linked list).
then middle digits 76 is the address. 1. Open Addressing
There is a difficulty for finding the mid-square of a Open addressing can be defined as one of the
large number. This can be overcome by assuming methods used for resolving the collisions. This process of
the first three digits and squaring them to get the resolution takes place in an area called as the prime area
hashed address. that consists of the home addresses. Whenever collision
7. Multiplication Method takes place, the prime area addresses will be scanned until
Knuth and Junth claim that another method, the open (or) vacant element is found. When an unoccupied
multiplicative hashing function, is quite useful. element is found the new data will be placed in that
For a non-negative integral key x and constant c position. Open addressing consist of four methods,
such that 0 < c < 1, the function is, (i) Linear Probing
H(x) = [m(cx mod 1)] + 1 In linear probing method of hashing, f is a linear
Here cx mod 1 is the fractional part of cx and [ ] function of i, typically f(i) = i. Linear probing is a simple
denotes the greatest integer less than or equal to open addressing strategy for collision handling. In this,
its contents. This multiplicative hashing function the cells are sequentially searched to find an empty cell.
should give good results if the constant c is properly
Given that,
chosen, a choice which is difficult to make.
keys: 16, 23, 43, 18, 34, 59, 30, 22
8. Universal Hashing
Universal hashing is used as a protection Size of Hash Table (HT) = 10
against malicious adversaries. In this method, Then, modular arithmetic function will be,
an arbitrary hash function is selected such that it h(x) = x% (size of HT)
is independent of the keys that would be stored. = x% 10
The hash function is selected from a carefully Initially, the Hash Table is empty.
designed set of functions.
Let φ be a finite collection of hash functions that
maps a universe of keys {0, 1, 2, 3, . . . ., n – 1}.
The total number of hash functions (h F ∈ φ) is Inserting 16
φ
approximately equal to m and φ is said to be For inserting the first key ‘16’ into this table, we
universal if, must compute h(x).
(i) (a, b) ∈ φ h(x) = x% 10
Where (a, b) is the distinct key pair. = 16% 10
(ii) hF(a) = hF(b) =6
If a function is arbitrarily selected from φ then So, the key 6 is inserted into 7th position.
the probability of collision between a and (a b)
1
would be equal to n .

155 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Inserting 23 Example
h(k) = 23% 10 = 3 The table below shows the result of inserting {79,
So, the key 23 will be inserted into 3rd position. 28, 39, 68, 59} into a hash table.

Inserting 43
h(k) = 43% 10 = 3
Collision will occur if 43 is placed at 3rd position
because 23 is already present there in that position. So the
next cell will be searched after 3rd which is 4th position.
Thus the key 43 is inserted in 4th position.

Table: Hash Table with Quadrating Probing After Inserting


Inserting 18 {79, 28, 39, 68, 59}
h(k) = 18% 10 = 8 While inserting the keys, the first collision occurs
Thus, the key 18 will be placed at 8th position. when 39 is inserted because 39 collides with 79. The
collision is resolved by inserting 39 into cell ‘0’ which
is one cell away from 79. Next 68 collides with 28, this
is resolved by moving one cell away. But, again another
Inserting 34 collision occurs. So, the cell is inserted in a cell that is
h(k) = 34% 10 = 4 22 = 4 cells away. Similarly, 59 is placed in cell 3.
If the key 34 is placed at 4th position, the collision The performance of linear probing degrades when
will occur. So, the next available cell is searched the hash table is nearly full. This situation for quadratic
after 4 which is 5. probing is even more serious. The quadratic probing
does not guarantee of finding an empty cell once the
Thus 34 will be inserted into 5th position.
table gets more than half full. And there is no guarantee
of finding an empty cell even before the table gets half
full, if the table size is not prime. Because, at most, half
Inserting 59 of the table is used to resolve collisions.
h(k) = 59% 10 = 9 But quadratic probing guarantees of inserting an
Thus, the key 59 will be inserted into 9th position. element into table. That is atleast half empty if the table
size is prime.
Proof
Assume that the table is a (odd) prime greater
Inserting 30
than 3 of size “size”. To proof this statement we show
h(k) = 30% 10 = 0 that the first size/2 alternatives locations (including initial
Thus, the key 30 will be placed at 0th position. location) are all distinct. Let the two locations are h(x)
+ i2 (mod size) and h(x) + j2 (mod size) where 0 ≤ i, j
≤ [size/2] and also assume that these locations are same
but i j. Then we have,
Inserting 22
h(x) + i2 = h(x) + j2 (mod size)
h(k) = 22% 10 = 2
i2 = j2 (mod size)
Thus, the key 22 will be placed at 2nd position.
i2 – j2 = 0 (mod size)
(i + j) (i – j) = 0 (mod size)
(ii) Quadratic Probing Since table size is prime, either (i – j) or (i + j)
Quadratic probing overcomes the clustering will equal to O(mod size). (i – j) can’t be zero since i
problem of linear probing. This is a collision resolution and j are distinct and (i + j) can’t be zero since 0 ≤ i
method where the collision function is quadratic. The and j ≤ [size/2]. Therefore the first [size/2] alternative
quadric probing function is expressed as f(i) = i2. In this locations are distinct.
method, when the collision occurs, the key is inserted Hence, there is guarantee of finding an empty cell
in a cell which is one cell away from the collided cell. if atmost [size/2] table is empty.

Publishers and Distributors Pvt. Ltd. 156


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
In quadratic probing, if table is even one more If double hashing is implemented correctly, then
than half full then insertion will fail. And if table size is the expected number of probes in doubling hashing is
not prime then the number of alternative locations can be almost same as for a random collision resolution strategy.
reduced severely. Further the deletion operation can’t be However quadratic probing is simple and fast because it
performed in open addressing hash table because there does not require a second hash function
might have been a collision at the cell to go past it.
2. Separate Chaining (or Linked List)
The quadratic probing overcome the drawback
primary clustering of linear hashing. But there is a In this type of hashing, the hash table stores a
problem in quadratic probing that the elements that hash set of pointers (rather than data elements); each pointer
to the same position will probe the same alternative cells. points to a separate linked list. The data elements are
This is known as secondary clustering. stored in the nodes of these linked lists. For each element
(iii) Double Hashing K, hash function (hf (k)) in applied, which gives the hash
code (index) of a particular bucket (cell) in the hash
Double hashing is a collision resolution method table. The element is stored in the linked list, which is
that uses the hashing function as f(i) = i.hash2(x). In this
associated with that bucket (cell).
hashing, the second hash function hash2(x) is applied to x
and probing is done at a distance hash2(x), 2hash2(x) . . . Example
and so on. Here the second hash function hash2(x) should
Keys to be inserted {3417, 3132, 7122, 5199,
be chosen carefully. This function should be chosen in
5344, 6796, 1898}
such a way that the function must never equal to zero. It
is good to have the table size prime. The function such Hash function hf (x) = x mod 10.
as hash2(x) = R – (x mod R) works well if R is a prime
Computing the hash values for each of the given
number smaller than the table size. For example, if R =
input using the hash function.
7 then the table below shows the results of inserting the
keys {89, 18, 49, 58, 69}. hf(3417) = 3417 mod 10 = 7 (7th bucket)
hf(3132) = 3132 mod 10 = 2 (2nd bucket)
hf(7122) = 7122 mod 10 = 2 (2nd bucket)
(collision occurred)
hf(5199) = 5199 mod 10 = 9 (9th bucket)
hf(5344) = 5344 mod 10 = 4 (4th bucket)
hf(6796) = 6796 mod 10 = 6 (6th bucket)
hf(1898) = 1898 mod 10 = 8 (8th bucket)

Table: Hash Table with Double Hashing After Inserting The resultant hash table for the keys given above
{89, 18, 49, 58, 69} will be,

The first collision occurs while inserting 49. This


collision is resolved by evaluating the function hash2(49)
= 7 – 0 = 7 so 49 is inserted in cell 6. Second collision
occurs when inserting 58. It is resolved by hash2(58) =
7 – 2 = 5, so 58 is inserted in position 3. Next when 69
collides it is inserted in position 0 at distance of hash2(69)
= 7 – 6 = 1 away. There are some bad cases if insertion
results into a series of collisions. For example, if we try
for inserting 60 in position 0, then it results in a sequence
of collisions at cells 3, 6, 9, since hash2(60) = 7 – 4 = 3.
This is tried until an empty spot is found.
The hash table size in the above example is not
prime. But it is desirable to have the table size as prime,
if it is not then it is possible to run out of alternative
locations prematurely. For example, if we try to insert
23 into above table it collides with 58. Since hash2(23)
= 7 – 2 = 5 and table size is 10 (even) we have only one
alternative location which is already occupied. Figure: Hashing with Chaining

157 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

EXERCIsE AND PRACTICE QUEsTIoNs

Short Questions
1. Define,
(i) Spanning tree (ii) Binary tree. (Refer Q2) May-18, Q3 [MGU]
2. What are the applications of trees? (Refer Q5) June/July-19, Q5 [OU]
3. Define the terms minimum spanning tree and connected
components with examples. (Refer Q6) May/June-18 Q5 [OU]
4. Briefly describe about the properties of a binary tree. (Refer Q7) Nov./Dec.-17, Q5 [OU]
5. What are the binary tree application? (Refer Q8) Nov./Dec.-19, Q5 [OU]
OR
What are the applications of Binary trees? (Refer Q9) May/June-19, Q3 [MGU]
6. Write the algorithm for post order traversal on a binary tree and
give an example. (Refer Q9) June/July-19, Q6 [OU]
7. Construct a binary tree using the following two traversals. (Refer Q10) Nov./Dec.-18, Q5 [OU]

Inorder D B H E A I F J C G
Preorder A B D E H C F I J G
8. Construct the binary tree from following:
In order 8,4,10,9,11,2,5,1,6,3,7. Find post order traversal. (Refer Q11) Nov./Dec.-17, Q3 [MGU]
9. Define graph and explain graph representation. (Refer Q12) Nov./Dec.-19, Q6 [OU]
OR
Describe the adjacency matrix and adjacency list graph
representations with example. (Refer Q12) Nov./Dec.-17, Q6 [OU]
10. Briefly discuss connected graph. (Refer Q14) Nov./Dec.-19, Q5 [MGU]
11. Explain how to represent the following graph using Inverse
Adjacency List. (Refer Q16) Nov./Dec.-18, Q6 [OU]

1 2 3
12. What is Hash Function? (Refer Q18) Nov./Dec.-18, Q3 [MGU]

13. Explain the hash function with any two implementation


methods. (Refer Q20) May/June-18 Q6 [OU]

Essay Questions
14. Define binary search tree. Construct a binary search tree and
explain the operations inserting a node, searching for a key,
deleting a node with examples. (Refer Q29) Nov./Dec.-17, Q11(a) [OU]

15. What are different traversal techniques for binary tree?


Explain about them with good examples. (Refer Q30) Nov./Dec.-17, Q7(a) [MGU]
OR
Define binary search tree. Explain pre-order, in-order, post-order
binary search tree traversals with examples. (Refer Q30) May/June-18, Q11(a) [OU]
OR
Describe about binary tree traversal techniques. (Refer Q30) May-18, Q7(a) [MGU]
16. Define the binary tree and explain its properties. Explain the
binary tree traversal techniques with example. (Refer Q31) Nov./Dec.-19, Q11(a)(i) [OU]

Publishers and Distributors Pvt. Ltd. 158


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III
17. Define Inorder traversal algorithm with an example. Write a C++
member function to implement non-recursive inorder traversal
algorithm of a binary tree. (Refer Q34) June/July-19, Q11(a) [OU]

18 Explain about properties of binary search tree. Construct binary


search tree for following:12,47,88,57,85,43,15,20. (Refer Q36) Nov./Dec-17, Q7(b) [MGU]
19. Write a program to travel binary tree in pre-order, post-order and
in-order. (Refer Q37) Nov./Dec-19, Q11(a)(ii) [OU]
20. Explain in detail about the application of binary trees. (Refer Q38) Nov./Dec.-19, Q9(a) [MGU]
21. Write the algorithm for the construction of Expression Tree.
Explain the steps to construct an expression tree for the
expression E = (a + b × c)/d. (Refer Q39) Nov./Dec.-18, Q11(a) [OU]
22. Write Graph ADT. Explain the following operations on a graph
with examples.
(i) Insert Vertex (ii) Delete Vertex
(iii) Insert Edge (iv) Delete Edge. (Refer Q42) June/July-19, Q11(b) [OU]

23. Explain the representation of graphs using the adjacency


matrix, adjacency list and adjacency multi-list. (Refer Q43) Nov./Dec.-18, Q11(b) [OU]

24. Briefly describe about the graph traversal techniques.For the


following graph, give the result of DFS and BSF traversals. (Refer Q44) May/June-18, Q11(b) [OU]

7
3
6

1 8

2
4

OR
Explain Depth-First-Search (DFS) method for Graphs. (Refer Q44) May/June-19, Q7(b) [MGU]

OR
Explain Breadth-First-Search (BSF) method for Graphs. (Refer Q44) Nov./Dec.-18, Q7(b) [MGU]

25. What is spanning tree and minimum spanning tree?


Construct minimum spanning tree using Kruskal’s algorithm. (Refer Q45) Nov./Dec.-19, Q11(b) [OU]
a 20 b 30 c 10 d
30 10 30 50
e 40 f 30 g 30 h
40 20 10 30
i 30 j 30 k 10 l

26. Explain Prim’s algorithms for spanning tree. (Refer Q47) May/June-19, Q7(a) [MGU]

27. Discuss about Kruskal algorithm. (Refer Q49) May-18, Q7(b) [MGU]

OR
Explain Kruskal’s algorithms for spanning tree. (Refer Q49) Nov./Dec.-18, Q7(a) [MGU]

28. Define the terms graph, tree, spanning tree, and minimum
spanning tree. Construct a minimum spanning tree (step-by-step)
from the following graph using prim’s algorithm. (Refer Q53) Nov./Dec.-17, Q11(b) [OU]
12
A B

17 1
3

15 F C
2
19 10
5
E D
14

29. Explain in detail about the basic concepts of hashing. (Refer Q54) Nov./Dec.-19, Q9(b) [MGU]

159 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

INTERNAL AssEssMENT/EXAM

I Multiple Choice
1. A tree node that has no children is called a ______ node. [ ]

(a) Leaf (b) Siblings

(c) Non-leaf (d) Ancestor

2. A node that is neither the root nor a leaf node is called as ______. [ ]

(a) Leaf node (b) Internal node

(c) External node (d) Parent node

3. A binary tree which contains only the left child nodes or only the right child nodes is called as
______. [ ]

(a) Full binary tree (b) Strictly binary tree

(c) Skewed binary (d) None of the above

4. Which of the following is not an operation of a binary tree? [ ]

(a) Traversal (b) Find

(c) Insert (d) Delete

5. The order of the post-order traversal ______. [ ]

(a) LVR (b) RVL

(c) RLV (d) LRV

6. A tree that has 2l nodes at level l is called as ______. [ ]

(a) Full binary tree (b) Strictly binary tree

(c) Complete binary tree (d) None of the above

7. The depth d of a complete binary tree T with n nodes is ______. [ ]

(a) 2n–1 (b) (log (n 1) 1) 2 2 + −

(c) d = n + 1 (d) log2 n + 1

8. Which one of the following is an application of a graph? [ ]

(a) Shortest path determination (b) Minimum cost spanning tree

(c) Both (a) and (b) (d) None of the above

9. The number of edges in a complete graph is equal to ______. [ ]

(a) 2 n(n−1) (b) 2 n

(c) n (d) n(n – 1)

10. The various collision resolution techniques are ______. [ ]

(a) Closed hashing(or) Open addressing (b) Open hashing

(c) Both (a) and (b) (d) None of above

Publishers and Distributors Pvt. Ltd. 160


UNIT-3: Trees, Graphs and Hashing Computer Science Paper-III

II Fill in the Blanks

1. Tree is a non-linear data structures that can be represented in a _____ manner.

2. The average and worst-case time taken to perform operations on balanced binary tree with n node is
_____.

3. A balanced binary tree is also called as _____.

4. A graph in which every edge is directed is known as _____

5. A pair of nodes connected by a line segment is called _____.

6. The two algorithms that are used to find minimum spanning tree are _____ and _____.

7. _____ selects an edge in the graph with minimum weight

8. _____ is a technique that makes use of a hash function for mapping pairs to the corresponding (entries)
positions in a hash table

9. In _____ method of hashing, f is a linear function of i, typically f(i) = i

10. _____ is a collision resolution method that uses the hashing function as f(i) = i.hash2(x)

KEY
I. Multiple Choice
1. (a) 2. (b) 3. (c) 4. (b) 5. (d)

6. (a) 7. (d) 8. (c) 9. (a) 10. (c)

II. Fill in the Blanks


1. Hierarchical

2. O(log n)

3. Height balanced binary tree

4. Directed graph

5. Edges

6. Kruskal’s Algorithm, Prim’s Algorithm

7. Kruskal’s algorithm

8. Hashing

9. Linear probing

10. Double hashing.

161 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

III Very Short Questions and Answers


Q1. Define tree.

Answer :

A tree is a non-linear data structure that can be represented in a hierarchical manner. It contains a finite set
of elements called ‘nodes’ which are connected to each other using a finite set of directed lines called ‘branches’.

Q2. What is connected graph?

Answer :

A graph is said to be connected if there exists a path between any two vertices U and V. Otherwise the graph
is disconnected.

Q3. Define minimum spanning tree.

Answer :

A minimum spanning tree is a spanning tree, that has weights with the edges and the total weight of the tree
(the sum of the weights of its edges) is at a minimum.

Q4. What is hashing?

Answer :
Hashing is a technique that makes use of a hash function for mapping pairs to the corresponding (entries)
positions in a hash table.
Q5. Why do we use decision trees?

Answer :
Decision tree is used to arrange the output of several decision in the desired order i.e., in the form of a tree.
It contains root node, internal nodes,leaf nodes. Internal nodes holds the conditions to be checked. The tree is
classified beginning at the root to the leaf node.

Publishers and Distributors Pvt. Ltd. 162


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III

UNIT
4 Searching and Sorting, Heaps

SYLLABUs
Searching and Sorting: Sequential (Linear) Search, Binary Search, Bubble Sort, Insertion Sort,
Selection Sort, Quick Sort, Merge Sort and Comparison of Sorting Techniques.

Heaps: Concept, Implementation, Abstract Data Type, Heap Sort.

LEARNING OBJECTIVEs
 Meaning of Searching and Sorting
 Linear and Binary Search
 Different kinds of Sorting Techniques
 Heap and its Implementation
 Heap Sort Technique.

INTRoDUCTIoN
Searching is a process of finding the correct location of an element from a list or array
of elements. In an array, elements are stored in consecutive memory locations.

Sorting is a technique of organizing the data or arranging the records either in ascending
or descending order. It is very easy and efficient to perform searching if data is stored in
order. The efficiency of sorting technique depends on utilization of memory, sorting time,
utilization of processor. The different sorting techniques includes selection, insertion,
bubble, quick, merge and heap. Each of these techniques have their own way of performing
the sorting process and have different time complexities.

A complete binary tree in which the value node is either greater than, lesser than or equal
to values in child nodes is called a heap.

163 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

P a r t- A S h o rt Q u e s t i o n s a n d A n s w e r s

Q1. Define searching. List various searching techniques.


Answer : Model Paper-I, Q10

Searching
Searching is a process of finding the correct location of an element from a list or array of elements. In
an array, elements are stored in consecutive memory locations. Searching is done by comparing a particular
element with the remaining elements until the exact match is found. If the element is found, the search process
is said to be successful or else the search process is terminated unsuccessfully. The time complexity of searching
technique depends on the number of comparisons made to find the exact match.
Searching Techniques
The searching techniques can be categorized into two types,
1. Sequential/Linear search
2. Binary search.
Q2. Explain linear search.
Answer : May/June-19, Q4 [MGU]

Linear Search
The sequential/linear search method is mainly applicable for searching an element within an unordered
list. The principle behind sequential/linear search is that each element of the list is compared or matched with
the key (i.e., search argument) in a sequential order. The search (i.e., comparison) begins from the starting
element and proceeds until a match is found or the end of list is encountered. If a match is found (i.e., successful
search), the position (i.e., index) of the matched element is returned. If a match is not found but the end of list is
encountered then – 1 is returned (i.e., unsuccessful search). rt a
nd Simple
Sho
Advantages of Linear Search
1. It is simple because it is easily understood as well as easily implemented.
2. It does not restrict the data to be stored in a sorted manner within the list.
Disadvantages of Linear Search
1. It is time consuming.
2. It is inefficient when large number of elements are present in a list.
Q3. Write how binary search works.
Answer : Model Paper-I, Q11

Binary search technique is implemented on sorted list of elements. It is relatively faster than linear search.
Moreover, this method performs efficient search irrespective of the size of the list.
The principle followed in binary search is “divide and conquer”. The search is initiated by dividing
the list into two sublists and computing the middle element. This element is then compared with the element
to be searched. If the middle element is same as desired element (say key element), the search is terminated
successfully, and the location (or index) of the middle element is returned. On the other hand, if the middle
element doesn’t match, then it is checked whether the middle element is greater than or less than the key element.
If middle element is greater, then search is performed on right sublist or else, the desired element is searched
into the left sublist. This process is repeated, until the desired item is found. If the desired element is not found,
then the search terminates unsuccessfully.
Q4. Explain the sequential search algorithm with an example.
Answer : Nov./Dec.-17, Q7 [OU]

Consider the following list.

4 10 5 15 6 30 40 9 7

Publishers and Distributors Pvt. Ltd. 164


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Let the element to be searched is ‘15’. The linear/sequential search algorithm starts from the first element
i.e., 4 and compares it with the key element i.e., 15.
The index element is set to ‘0’.
List 4 10 5 15 6 30 40 9 7 (4 ≠ 15)

i=0

Since 4 ≠ 15, ‘i’ is moved to the next element i.e., 10.


Now the element at i = 1 is compared with the key element 15.
List 4 10 5 15 6 30 40 9 7 (10 ≠ 15)

i=1

Since 10 ≠ 15, ‘i’ is moved to the next element i.e., 5.


Now, the element at i = 2 is compared with the key element 15.
List 4 10 5 15 6 30 40 9 7

i=2
Since, 5 ≠ 15, ‘i’ is moved to the next element i.e., 15.
Now, the element i = 3 is compared with the key element ‘15’.
List 4 10 5 15 6 30 40 9 7

i=3
Since, the current element matches with the key element (i.e., 15 = 15) at location i = 3, the search is
successful and the location of element ‘i’ i.e., 3 is returned upon success.
Q5. Write a program for sequential search.
Answer : Nov./Dec.-19, Q7 [OU]

For answer refer Unit-IV, Page No. 174, Q.No. 22, Topic: Program.
Q6. List the advantages and disadvantages of binary search. Nov./Dec.-19, Q6 [MGU]
OR
What are the Pros of binary search?
ant Like Wa
po r t ter
(Refer Only Topic: Advantages of Binary Search) Im

Answer : Nov./Dec.-18, Q7 [OU]


Advantages of Binary Search
1. It is efficient when large numbers of elements are present in the list.
2. It is a faster searching technique.
3. It relatively requires less number of comparisons when compared to linear search.
Disadvantage of Binary Search
It restricts the data in the list to be stored in a sorted manner.
Q7. Differentiate between linear search and binary search.
Answer : Model Paper-II, Q10

Linear Search Binary Search


1. It works both on sorted list as well as on 1. It works only on sorted list of elements.
unsorted list.
2. It doesn’t require middle element to be 2. It requires middle element to be accessed.
accessed.
3. It is not compulsory to perform sorting each 3. It is compulsory to perform sorting each time an
time an element is inserted. element is inserted.

165 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Q8. Define sorting. State the need for sorting. Iteration 1
Answer : Model Paper-III, Q10 Step 1
Sorting Compare the first two elements since, 2 < 10
Sorting is a technique of organizing the data or exchanging of element’s position is not required.
arranging the records either in ascending or descending 2 10 6 4 8 No
order (i.e., bringing some orderliness in the data). Sorting change
can be performed on any one or combination of one or
more attributes present in each record. It is very easy and
efficient to perform searching, if data is stored in sorted Step 2
order. The efficiency of a sorting technique depends Compare the next two elements
on utilization of memory, sorting time, utilization of
2 10 6 4 8
processors, etc. For instance, sorting can be used to
arrange the names of the persons in the telephone diary
in ascending order of alphabets(i.e., A to Z). Since 10 > 6, exchange position of 10 with posi-
Need of Sorting tion of element 6.
Sorting is needed so as, 2 6 10 4 8
(i) To support the searching process. Step 3
(ii) To match the entries in the list. Compare element 10 with element 4
Q9. Where is the sorting used in computer 2 6 10 4 8
science?
Answer :
Since, 10 > 4, exchange position of 10 with position
Applications of sorting in computer science,
of 4.
(i) Sorting is used for discovering patterns or statis-
tics of data items. 2 6 4 10 8
(ii) It is used in comparing lists (or sets). Step 4
(iii) It is used in performing set operations i.e., finding Compare element 10 and 8
the lists with common elements, finding the list
2 6 4 10 8
with duplicate elements.
Q10. Define internal and external sorting.
Answer : June/July-19, Q7 [OU] Since, 10 > 8 exchange position of 10 with position
Internal Sorting of 8.
If sorting is performed on the list of elements that 2 6 4 8 10
are stored in main memory then it is called as ‘’internal
As the end of array is reached the iteration 1
sorting’’. Internal sorting methods
are in turn divided into several terminates. The last element 10 does not require
categories. They are, further processing.
(i) Insertion sort Iteration 2
(ii) Selection sort Step 1
(iii) Exchange sort (eg: Bubble I am Simple and Easy Compare element 2 with 6
sort, quick sort). 2 6 4 8 10
External Sorting
If sorting is performed on the list of elements Since, 2 < 6 exchanging of an element’s position
that are stored in secondary or external memory then is not required.
it is called as ‘’External sorting’’. One of the external Step 2
sorting method is Merge sort.
Compare element 6 with 4
Q11. Apply the bubble sort algorithm to sort
the list of data: 2,10,6,4,8. 2 6 4 8 10
Answer : May/June-18, Q7 [OU]
Bubble Sort Since, 6 > 4 exchange position of 4 with position
of 6.
The given list of data is 2,10,6,4,8
2 4 6 8 10
Consider the following list of data 2,10,6,4,8.

Publishers and Distributors Pvt. Ltd. 166


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Step 3 Q12. Write the working principle of quick sort
Compare the element with 8 and merge sort.
Answer :
2 4 6 8 10
Quick Sort
The principle of quick sort is to divide and con-
Since, 6 < 8 exchanging of an element’s position quer the unsorted list. Quick sort is the most power-
is not required. ful sorting algorithm. It uses the policy of divide and
conquer. It is also known as partition exchange sort.
2 4 6 8 10 Suppose there are ‘n’ elements in the list which are to
be sorted. Quick sort method divides the list into two
This is end of iteration 2, 8 is patched before with
sublists based on an element called pivot element or
the element 10. key. Usually, the first element in list is the pivot ele-
Iteration 3 ment.
Merge Sort
Step 1
Merge sort uses divide and conquer approach
Compare element 2 with element 4 to sort a given list. It divides the list into n sublists of
equal size until only one element is left in the list. After
2 4 6 8 10 that, it recursively applies merge sort on sorted sublists
to form a combined list.
Since, 2 < 4 exchanging of an element’s position Q13. Sort the elements using quicksort:
is not required. 52,38,81,22,48,13,69,93.
Answer : Nov./Dec.-17, Q4 [MGU]
Step 2
Sorting the follow-
Compare element 4 with 6 ing elements using quick sort: If I Don’t Come,
2 4 6 8 10 52,38,81,22,48,13,69,93. My Method Will Come

52 38 81 22 48 13 69 93

Since, 4 < 6 exchanging of an element’s position Key i j


is not required.
52 38 81 22 48 13 69 93
2 4 6 8 10

This is end of the iteration 3, the element 6 is


Key i j
patched before the element 8.
Iteration 4 52 38 81 22 48 13 69 93

Compare element 2 with 4


Key i j
2 4 6 8 10
a[i] > a[key] the i stops incrementing
52 38 81 22 48 13 69 93
Since, 2 < 4 exchanging of an element’s position
is not required.
Key i j
2 4 6 8 10
i > j swap i and j
This is end of the iteration 4, the element 4 is 52 38 69 22 48 13 81 93
patched before the element 6.
Since, the only element left is 2, it is patched Key i j
before 4.
Swap i and j, then
Finally, the completely sorted list of elements
52 38 13 22 48 69 81 93
obtained is given below,

2 4 6 8 10
Key i j

167 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
52 38 13 22 48 69 81 93 Consider j = right, i = left and 10 as pivot element
Step 2

Key i j 10 6 3 7 17 26 56 32 72

a[j] < a[key] swap a[j] with a[key]


Key i j
52 38 13 22 52 69 81 93
Step 3
Key element 10 6 3 7 17 26 56 32 72
Now, repeat the process on the elements at the
left side of the pivot element.
Key i j
48 38 13 22
Step 4
10 6 3 7 17 26 56 32 72
Key i j
48 38 13 22
Key i j
Step 5
Key i j
10 6 3 7 17 26 56 32 72
a[j] < a[key] swap a[j] with a[key]
22 38 13 48
Key i j
Here, A[i] > A[key] therefore i stops incrementing,
Key i j
Step 6
22 38 13 48
10 6 3 7 17 26 56 32 72

Key i j
Key i j
a[j] < a[k] swap a[j] with a[key]
Step 7
13 38 22 48
10 6 3 7 17 26 56 32 72

Key i j
Key i j
swap i and j
13 38 22 48 Step 8
10 6 3 7 17 26 56 32 72
∴ The sorted element are,
13 22 38 48 52 69 81 93
Key i j
Q14. Rearrange following numbers using quick
sort. Step 9
10,6,3,7,17,26,56,32,72. 10 6 3 7 17 26 56 32 72
Answer : (Model Paper-I, Q12 | May-18, Q4 [MGU])

Consider the following elements to be sorted, Key i j


10 6 3 7 17 26 56 32 72
Step 10
Applying quick sort method to sort the elements,
10 6 3 7 17 26 56 32 72
Step 1
10 6 3 7 17 26 56 32 72
Key j i
Key
Left Right A[j] < A[key] swap A[j] with A[key]

Publishers and Distributors Pvt. Ltd. 168


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Step 11 Q15. What are the time complexities of
various sorting algorithms?
7 6 3 10 17 26 56 32 72
Answer : Model Paper-III, Q12
The time complexities of various sorting tech-
Key j i niques are listed in the table,
A[j] < A[key] swap A[j] with A[key] Sorting Time Complexities
Techniques
3 6 7 10 17 26 56 32 72 Average Best Worst
Case Case Case
Insertion Sort O(n2) n–1 O(n2)
Pivot element
Selection Sort O(n )2
O(n2) O (n2)
Now, repeat the process on the elements at right Quick Sort O(n logn) O(n logn) O(n2)
side of the pivot element Merge Sort O(n logn) O(n logn) O(n logn)
17 26 56 32 72 Bubble Sort O(n2) O(n2) O(n2)
Table: Time Complexity of Sorting Techniques
17 26 56 32 72
Q16. Define a heap with an example.
Key June/July-19, Q8 [OU]
i i
OR
17 26 56 32 72 Define a heap. Build the heap tree for the
list of data.
Answer : (Model Paper-II, Q11 | Nov./Dec.-17, Q8 [OU])
Key i j
Heap
A[i] > A[key] therefore i stops incrementing A complete binary tree in which the value node
17 26 56 32 72 is either greater than, lesser than or equal to values in
child nodes is called a heap.
Heap Tree
Key i j
Heap tree for the given list of data: 2,9,7,6,5,8
17 26 56 32 72 Insert 2
2
Key i j
Insert 9
17 26 56 32 72
2
Remember me
with concept
Key i j
9
Now, consider the last three elements,
Insert 7
56 32 72
2

Key i j
9 7

56 32 72
Insert 6
2
Key i j

A[i] < A[key] swap A[i] with A[key] 9 7


32 56 72
6
∴ The sorted list for the given elements is,
3 6 7 10 17 26 32 56 72 9 > 6 swap 9 and 6

169 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Algorithm (Construct Heap)
2
Step1: Consider a heap tree which is empty. Begin at the
first step,
6 7
i=1
while (i < = n) do
9
Insert 5 Step2: Repeat step 2 for all the elements
Step2.1: Select the ith element from list and add an
2
element to the ith place in array
n = Arr[i]
6 7
Arr1[i] = n
j=i
9 5
Step2.2: Repeat step 2.2 to step 2.3 until the root is
checked
6 > 5 so swap 6 and 5
If Arr[j] > Arr1[j/2] then
2 tmp = Arr1[j]
Arr1[j] = Arr1[j/2]
5 7 Arr1[j/2] = tmp
j = j/2
9 6 else
j=1
Insert 8
End If
2 Step2.3: End while
i = i +1
5 7 Step2.4 : End while
Step3: Stop
9 6 8 Q18. Explain the concepts of min-heap and
max-heap with examples.
\ The following is the resultant heap tree. May/June-18, Q8 [OU]

OR
2
Define minheap and maxheap with ex-
amples.
5 7 Answer : (Model Paper-III, Q11 | Nov./Dec.-18, Q8 [OU])

Min Heap
9 6 8 An ascending heap of size ‘n’ can be defined as
a complete binary tree of n nodes such that the content
Q17. What is heap? Explain heap construction of each node is greater than or equal to its parent.
process? Example
Answer : Nov./Dec.-19, Q8 [OU]

Heap Hey!
Don’t
For answer refer Unit-IV, Page escape
No. 169, Q.No. 16, Topic: Heap. from
me
Heap Construction Process
In this phase, an array based list is transformed into
a heap. The array based list can be viewed as a binary
tree, in which a binary tree would be called a heap if
each node in it is greater than or equal to its left and
right children. Figure: Ascending Heap Tree

Publishers and Distributors Pvt. Ltd. 170


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Max Heap Q20. Define Heap sort. How efficiency of heap
A descending heap of size ‘n’ can be defined as sort is calculated?
a complete binary tree of n nodes such that the content Answer :
of each node is less than or `equal to its parent.
Heap Sort
Example
In heap sort, the order of equal elements change
during reconstruction of heap or when swapping “root
element with last element of heap”.
Efficiency of Heap Sort
Heap sort technique works in two phases i.e.,
building or constructing heap of a list and sorting the
heap. To find the efficiency of heap sort consider only
second phase i.e., sorting phase of heap sort.
Figure: Descending Heap Tree
Basically, the heap-sort technique has a loop that
Q19. What is heap Abstract Data Type?
iterates until all data is sorted. Inside this loop there is a
Answer : (Model Paper-II, Q12 | Nov./Dec.-18, Q4 [MGU]) recursive call to a function reheapDown( ).
A binary tree which is complete and satisfies Loop(for all elements of list)
the heap order property is called as Heap. The basic
operations that are performed on it are insert, delete, reheapDown( );
max-heap and min-heap. The class definition for heap
/* Recursive call or loop */
ADT is as follows,
class Node End loop

{ The outer loop executes ‘n’ times and the inner


recursive call shows a path of following the branches of
int Arr[max];
a binary tree, which requires ‘logn’ loops. Therefore, the
int x; overall complexity becomes O(n log n).
};
class Heap
{
private:
Node *Root;
void ReHeapUp(int i);
void ReHeapDown(int i);
public:
Heap( )
{
for(int i = 0; i<Max; i++)
Arr[i] = 0;
}
void Create( );
void Insert(int n);
void DeleteMaxVal( );

};

171 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

P a r t- b E S S AY Q u e s t i o n s a n d A n s w e r s

4.1 Searching and sorting

4.1.1 Sequential (Linear) Search, Binary Search


Q21. What is searching? Explain various types of searching technique.

OR
Explain different searching techniques with example. Nov./Dec.-18, Q8(a) [MGU]

OR
Write the binary search algorithm and trace the steps followed to find 88 in the following
list 8,12,24,28,32,45,48,51,56,62. May/June-18, Q12(a) [OU]
(Refer Only Topic: Binary Search)
OR
Discuss Binary Search algorithm with an example. Write down the Pros and Cons of binary
search method.
(Refer Only Topic: Binary Search)
Answer : (Model Paper-I, Q19 | June/July-19, Q12(b) [OU])
Searching
Searching is a process of finding the correct location of an element from a list or array
of elements. In an array, elements are stored in consecutive memory locations. Searching is
done by comparing a particular element with the remaining elements until the exact match I am a
Repeated
is found. If the element is found, the search process is said to be successful or else the search Question

process is terminated unsuccessfully. The time complexity of searching technique depends


on the number of comparisons made to find the exact match.
Searching Techniques
The two different searching techniques are as follows,
1. Sequential/Linear search
2. Binary search.
1. Sequential/Linear Search
The sequential/linear search method is mainly applicable for searching an element within an unordered
list. The principle behind sequential/linear search is that each element of the list is compared or matched with
the key (i.e., search argument) in a sequential order. The search (i.e., comparison) begins from the starting
element and proceeds until a match is found or the end of list is encountered. If a match is found (i.e., successful
search), the position (i.e., index) of the matched element is returned. If a match is not found but the end of list is
encountered then – 1 is returned (i.e., unsuccessful search).
Example
Consider the following list.
4 10 5 15 6 30 40 9 7

Let the element to be searched is ‘15’. The linear/sequential search algorithm starts from the first element
i.e., 4 and compares it with the key element i.e., 15.
The index element is set to ‘0’.
List 4 10 5 15 6 30 40 9 7 (4 ≠ 15)

i=0
Since 4 ≠ 15, ‘i’ is moved to the next element i.e., 10.

Publishers and Distributors Pvt. Ltd. 172


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Now the element at i = 1 is compared with the key element 15.
List 4 10 5 15 6 30 40 9 7 (10 ≠ 15)

i=1
Since 10 ≠ 15, ‘i’ is moved to the next element i.e., 5.
Now, the element at i = 2 is compared with the key element 15.

List 4 10 5 15 6 30 40 9 7

i=2
Since, 5 ≠ 15, ‘i’ is moved to the next element i.e., 15.

List 4 10 5 15 6 30 40 9 7

i=3
Since, the current element matches with the key element (i.e., 15 = 15) at location i = 3, the search is
successful and the location of element ‘i’ i.e., 3 is returned upon success.
Time Complexity of Linear Search
Time complexity of linear search is O(n). It requires atmost ‘n’ comparisons to search an element in a list
containing ‘n’ elements.
2. Binary Search
Binary search technique is implemented on sorted list of elements. It is relatively faster than linear
search. Moreover, this method performs efficient search irrespective of the size of the list.
The principle followed in binary search is “divide and conquer”. The search is initiated by dividing the
list into two sublists and computing the middle element. This element middle is then compared with the element
to be searched. If the middle element is same as desired element (say key) element, the search is terminated
successfully, and the location (or index) of the middle element is returned. On the other hand, if the middle
element doesn’t match, then it is checked whether the middle element is greater than or less than the key element.
If middle element is less than the search is performed on right sublist or else, the desired element is searched into
the left sublist. This process is repeated, until the desired element is found. If the desired element is not found,
then the search terminates unsuccessfully.
Example
The given list is 8,12,24,28,32,45,48,51,56,62 and the key element to find is 88.
Consider the following ordered list having 10 elements
List 8 12 24 28 32 45 48 51 56 62
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

Low_val High_val
Given that, the element be to searched is 88. Initially, the middle (or center) element is determined by using
the formula,
Low –val + High –val 0+9
Mid_val = = =4
2 2
Left sublist Right sublist

8 12 24 28 32 45 48 51 56 62
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

Low_val Mid_val High_val

173 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Now, compare the key element ‘88 with the value Advantages of Binary Search
at index ‘Mid_val’ i.e 32. Since, 32 ≠ 88 and moreover 1. It is efficient when large numbers of elements
32 < 88. Therefore the key element is searched in the are present in the list.
right sublist i.e., given below, 2. It is a faster searching technique.
List 45 48 51 56 62 3. It relatively requires less number of
comparisons when compared to linear search.
[0] [1] [2] [3] [4]
Disadvantage of Binary Search
It restricts the data in the list to be stored in a
Low_val High_val sorted manner.
The middle element for the new list is calcu- Q22. Write the algorithm and program for
lated as follows, sequential search.
Answer :
Low –val + High –val 0+4
Mid_val = = =2 Algorithm
2 2
Algorithm SequentialSearch(array, end, target, address).
List 45 48 51 56 62
/*Begin: array contains unordered list of
[0] [1] [2] [3] [4] elements, target is the key to be searched in the
list, address is the index, end is the index of last
Low_val Mid_val High_val element in the list*/
Begin
Now, compare the key element ‘88’ with the value set k to 0 i.e., k = 0;
at index ‘Mid_val’ i.e., 51. Since, 51 ≠ 88 and more ever loop(k <end AND target not equal to array [k])
51 < 88. Therefore, the key element is searched in the k = k + 1;
right sublist that is given below, end loop
List 56 62 address = k;
[0] [1] If(target equal to array[k])
result = true;
else
Low_val High_val
result = false;
Middle value is calculated as follows, end if
Low –val + High –val return result;
0 +1
Mid_val = = =0 end SequentialSearch
2 2
List 56 62 Program
#include<iostream>
[0] [1]
#include<conio.h>
using namespace std;
Low_val High_val class linearsearch
Mid_val {
Now, compare the key element ‘88’ with the value public:
at index ‘Mid_val’ i.e., 56. Since 56 ≠ 88 and moreover int data[10],n,element;
56 < 88. Therefore, the key element is searched in the void getele( );
right sublist of the above list that contains 62. void display( );
};
List 62
void linearsearch :: getele( )
∴ The value of the list is 62 which is not equal {
to key element. Therefore, the key element is not found. cout<< “\nEnter the size of the array:”;
Time Complexity of Binary Search cin>>n;
cout<< “Enter the elements:\n”;
A non-recursive binary search algorithm uses
for(int i=0;i<n;i++)
a while loop. The number of iterations will depends
on the number of elements in the list. In a worst case, {
the search requires O(log n) iterations where n is the cin>>data[i];
number of elements in the list. }

Publishers and Distributors Pvt. Ltd. 174


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
cout<< “Enter the element to be find in the given array:”; Algorithm
cin>>element; The sentinel search algorithm is given below,
} Algorithm SentinelSearch(array, end, target, address)
void linearsearch :: display( ) /*Begin: array contains unordered list of elements
{ target is the key to be searched in the list
int flag=0; address is the index
for(int i=0;i<n;i++) end is the index of last element in the list */
{ array[end + 1] = target;
if(element== data[i])
set k to 0 i.e., k = 0;
{
loop (target not equal to array[k]]
cout<< “Search Successful!
k = k + 1;
\nThe element found at location:”<<i;
flag++; end loop
} if k is less than or equal to end then
} result = true;
if(flag==0) address = k;
cout<< “Search Unsuccessful!!”; else
} result = false;
int main( ) address = end;
{ end if
linearsearch ob; return result;
ob.getele( ); end SentinelSearch
ob.display( ); 2. Probability Search
return 0; Probability search is another useful variation of the
} sequential search. The elements of an array which have
Output more probability of search are placed at the beginning of
the list and the elements with least probability of search
are placed at the end. The probability search is more
useful when the target elements for most of the searches
are relatively few. By swapping the located element with
the element immediately before it in the list for every
search, it can be ensured that, the ordering of elements
Q23. Discuss the three variants of a sequential according to their probability is correct.
search algorithm. Algorithm
Answer : The probability search algorithm is given below,
Algorithm Probability_Search(array, end,
The variants of a sequential search includes,
target, address)
1. Sentinel search
/*Begin: array contains elements
2. Probability search and ordered according to probability of search
3. Ordered list search. target is the element to be searched in the list
1. Sentinel Search address is the index
A sentinel search tries to reduce two or more conditions end is the index of last element in the list */
that are tested in the inner loop to just one condition. search the target in the array
For example, the sequential search algorithm tests if(target is found in array) then
for conditions, result = true;
(i) The end of the list address = index of element containing target;
(ii) The target found or not. if(target is found after first element)
If it is confirm that, the target element will be move up the target element by one location
found in the array then the condition for testing the end of end if
the list can be eliminated. This can be achieved by adding else
an additional element called the sentinel element at the
result = false;
end of the array and placing the target in the sentinel. This
ensures that, the element is present in the list. After the end if
execution of the loop, it can be determine that, whether return result;
the sentinel element or the actual data is found. end Probability_Search

175 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
3. Ordered List Search end loop
If the array is ordered on the key (target) and set address = mid_val;
contains less number of elements then it is efficient to if(target equal to array[mid_val])
use ordered list search instead of using binary search for set result = true;
ordered list. In ordered list search, it is not necessary to else
search upto the end of the list for the key/target element. set result = false;
If the target is less than or equal to the current element
end if
then stop the search process here itself. In addition, the
concept of sentinel element can be used to eliminate return result;
the need for testing the end of the list when the target end binSearch
is greater than the last item. In this case, the sentinel Program
element becomes the last item. #include<iostream>
Algorithm #include<conio.h>
The algorithm for Ordered list search is given below, using namespace std;
Algorithm orderedSearch(array, end, class binary_search
target, address) {
/*Begin: array contains ordered elements int num[50],size,search;
end is the index of the last element public:
target is the element to be located. void getele(void);
address is the index*/ int searchfun(void);
if(target< end)then void display(void);
find the first element such that, it is less than };
or equal to target void binary_search :: getele(void)
address = index; {
else cout<<“Enter size of the array:”;
address = end; cin>>size;
end if cout<<“Enter the array elements in
if(target is found in array) Ascending order:\n”;
result = true; for(int i=0;i<size;i++)
else cin>>num[i];
result = false; cout<<“Enter the Search element:”;
cin>>search;
end if
}
return result;
int binary_search :: searchfun(void)
end
{
Q24. Write the algorithm and program for
binary search. int bottom=0,top=size –1,mid;
Answer : while(top >= bottom)
{
Algorithm
mid=(top+bottom)/2;
Algorithm binSearch(array, end, target, address)
if(num[mid]==search)
/*Begin: array contains an unordered list of
elements, target is the key to be searched in the return(mid+1);
list, address is the index, end is the index of last else
element in the list*/ {
set low_val = 0 and high_val = last; if(num[mid] < search)
loop(low_val < = high_val) bottom=mid+1;
set mid_val = (low_val + high_val)/2; else
if(target>array[mid_val]) top=mid;
set low_val = mid_val + 1; }
else if(target<array[mid_val]) }
set high_val = mid_val – 1; return(-1);
else }
set low_val = high_val + 1; void binary_search :: display(void)
end if {

Publishers and Distributors Pvt. Ltd. 176


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
int result; Q26. Analyze the efficiency of sequential
result=searchfun( ); search and binary search.
if(result== –1) Answer :
cout<<“The element is not found”;
else The algorithms are analyzed inorder to find which
cout<<“The element is found at is most efficient one.
location:”<<result–1; Efficiency of Sequential Search
}
int main( ) The basic principle of looping statement in
{ sequential search is given below,
binary_search o1; loop(k < end AND target not equal to array[k])
o1.getele( );
o1.display( ); k = k + 1;
return 0; This is an example of sequential algorithm which
} searches linearly. So, it is said to be linear search and the
Output
efficiency is O(n).
The efficiency of variant of sequential search is
as follows,
 The efficiency of sentinal search is O(n). As the
sentinel search is identical to sequential search
Q25. Write how the binary search is different interms of its design.
from linear search.
 The efficiency of ordered list search is also O(n).
Answer :
 The efficiency of probability search cannot be
Linear Search Binary Search determined unless the probability of each element
1. It works both on 1. I t w o r k s o n l y in the list is known.
sorted list as well on sorted list of When the list contains unordered elements and
as on unsorted list elements. data elements in the list are not directly accessible then
of elements.
sequential search is more efficient.
2. It doesn’t require 2. It requires middle
middle element element to be Efficiency of Binary Search
to be accessed accessed. The binary search algorithm always divides the
during the search array into two parts inorder to find out an element. That
process. is, the binary search logarithmic loop is given below,
3. It is not 3. It is compulsory to
loop(low_val < = high_val)
compulsory to perform sorting each
perform sorting time an element is set mid_val = (low_val + high_val)/2;
each time an inserted.
if(target > array [mid_val])
element is
inserted. set low_val = mid_val + 1;
4. It is an efficient 4. It is an efficient else if (target <array[mid_val])
search process, if search process, if the
set high_val = mid_val – 1;
the elements in the element in the list are
list are less. sorted. else
5. It requires more 5. I t r e q u i r e s l e s s set low_val = high_val + 1;
number of n u m b e r o f
end if
comparisons. comparisons.
6. It is easy search 6. It is a complicated end loop
technique. search technique. So, the efficiency of binary search is O(logn).
7. Complexity of this 7. Complexity of this
The comparison of linear and binary searches
search is O(n). search is O(logn).
with respect to the size of the list is as shown below,

177 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

List Size
16 50 256 1000 10,000 100,000 1000,000
Search
Number of iterations in SequentialSearch 16 50 256 1000 10,000 100,000 1,000,000
Number of iterations in BinarySearch 4 6 8 10 14 17 20

This shows that, binary search is an efficient algorithm for searching a list of any significant size. However,
it should not be used for small lists containing less than ‘16’ elements.

4.1.2 Bubble Sort


Q27. Write the algorithm, time complexity for bubble sort and explain with an example.
Model Paper-I, Q20(a)
OR
Write a program for sorting the numbers in ascending order using bubble sort.
(Refer Only Topic: Program)
Answer : Nov./Dec.-19, Q12(a)(ii) [OU]

Bubble Sort
Solve Me with Concentration
Bubble sort is a simple sorting technique in which after each pass the largest element
is bubbled up to its correct position.
The principle of bubble sort is to organize the list of elements by uniformly checking the two adjacent
elements and accordingly adjusting their positions. The sorting starts by initially comparing the first two adjacent
elements with each other. If the first element is greater than the second element, then these positions are exchanged.
Otherwise, the elements are at their own positions. Next, comparison is done between the second element and third
element. Their positions are exchanged if second element is larger than the third element. Otherwise elements
remain in their existing positions. In similar fashion, all the subsequent elements are compared with each other
and exchanged if required. This comparison is repeated till the last element is reached. This last element will be
the largest element and is placed at its correct position. This process is repeated until all the elements are sorted
in ascending order and till all the elements are bubbled up from last element to first element.
Example
Consider the following elements in the list:
8, 22, 9, 7.
Iteration 1 or Pass 1
Step1: Compare the first two elements. Since 8 <22 exchanging of element’s position is not required.
8 22 9 7 No Change

Step2: Compare the next two elements.


8 22 9 7

Since 22>9, exchange position of 22 with position of 9.


8 9 22 7

Step3: Compare element 22 with element 7.


8 9 22 7

Since 22 > 7, exchange position of ‘22’ with position of ‘7’.


8 9 7 22

As the end of array is reached, the iteration 1 terminates. The conclusion of each iteration will be the placement
of highest element at the end of the array. Hence, the last element is 22 which does not require further processing.

Publishers and Distributors Pvt. Ltd. 178


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Iteration 2 or Pass 2 Time Complexity
Step1: Compare element 8 with element 9. Since The time complexities (i.e., worst case, average
8<9, exchanging of element’s position is not case and best case) of bubble sort are shown in the
required. table below,

8 9 7 22 Case Time Complexity


Worst Case O(n2)
Average Case O(n2)
Step2: Compare element 9 with element 7.
Best Case O(n2)
8 9 7 22
Program
#include <iostream>
Since 9>7, exchange the position of element 9 #include <conio.h>
with that of element 7. #define MAX 10
7 9 22 using namespace std;
8
class bubblesort
This is the end of iteration 2. The element 9 is {
patched before the element 22. int arr[MAX],n;
9 22 public:
8 7
void getele( );
Iteration 3 void showele( );
void sortele( );
Compare element 8 with element 7.
};
8 7 9 22 void bubblesort :: getele( )
{
cout<< “Enter the size of an array:”;
Since 8 >7, exchange the position of element 8 cin>>n;
with that of element 7.
cout<< “Enter the elements of an array to be
7 8 9 22 sorted:\n”;
for(int i=0;i<n;i++)
Finally, the completely sorted list of elements cin>>arr[i];
obtained are given below: }
7 8 9 22 void bubblesort :: showele( )
{
Algorithm cout<< “The array after performing bubble
sort is:\n”;
Step 1 : Initialize index element i=1
for(int i=0;i<n;i++)
Step 2 : Repeat step 3 to step 11 until all the elements cout<<arr[i]<< “ ”;
are sorted.
}
Step 3 : Set j to n–1 void bubblesort :: sortele( )
Step 4 : If sortList[j]≤ sortList[j+1] then go to step 8 {
Step 5 : Set temp to sortList[j+1] int tmp, exchang=0;
for(int i=0;i<n;i++)
Step 6 : Set sortList[j+1] to sortList[j]
{
Step 7 : Set sortList[j] to temp. for(int j=0;j<n;j++)
Step 8 : Increment i and store the value in itself. {
Step 9 : If i ≤ j then goto step 4. if(arr[j] > arr[j+1])
Step 10 : Set j to j–1 {
tmp = arr[j];
Step 11 : If j ≥1 then go to step 1
arr[j] = arr[j+1];
Step 12 : Print the elements after sorting.
arr[j+1] = tmp;
Step 13 : End exchang++;

179 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
} Step4: Element 8 is compared with element 2.
} 5 3 7 8 2 9 1
if(exchang==0)
break;
} Since 8 > 2, exchange the position of element
} 8 with position of element 2. Then the resulting series
int main( ) will be as shown below,
{ 5 3 7 2 8 9 1
bubblesort obj;
obj.getele( ); Step5: Now, element 8 is compared with element 9.
obj.sortele( ); 5 3 7 2 8 9 1
No change
obj.showele( );
return 0;
Since 8 < 9, positions of these elements need
} not be exchanged.
Output
Step6: Element 9 is compared with element 1.
5 3 7 2 8 9 1

Since 9 > 1, exchange the position of element


Q28. Sort the list 5 ,8, 3, 7, 2,9, 1 using the 9 with position of element 1. Then the resulting series
bubble sorting method. will be as shown below,
Answer : 5 3 7 2 8 1 9

The elements in the list are 5, 8, 3, 7, 2, 9, 1


which are to be sorted in ascending order. The number As the end of elements is reached, this
of iterations and their explanations is given below, terminates the iteration 1. The conclusion of each end
of iteration will be placement of highest element at the
Iteration 1
end of the array. Hence, the last element obtained is 9,
Step1: Initially , the first two elements i.e., 5 and 8 which doesn’t require further processing.
are compared. Since 5<8 , there is no need to
Iteration 2
exchange the positions of these elements.
Step1: Element 5 is compared with 3.
3 1 No change 5 3 7 2 8 1 9
5 8 7 2 9

Step2: Now, element 8 is compared with element 3. Since 5 > 3, exchange the position of element
5 with position of element 3. Then the resulting series
5 8 3 7 2 9 1
will be as shown below,
3 5 7 2 8 1 9

Since 8>3 exchange the position of element 8 Step2: Now, element 5 is compared with element 7.
with that of element 3. Then the resulting series will
3 5 7 2 8 1 9
be as shown below: No change

5 3 8 7 2 9 1
Since 5 < 7, the position of these elements need
not be exchanged.
Step3: Element 8 is compared with element 7.
Step3: Element 7 is compared with element 2.
5 3 8 7 2 9 1
3 5 7 2 8 1 9

Since 8 >7, exchange the position of element 8 Since 7 > 2, exchange the position of element
with that of element 7. Then, the resulting series will 7 with position of element 2. Then the resulting series
be as shown below: will be as shown below,
5 3 7 8 2 9 1
3 5 2 7 8 1 9

Publishers and Distributors Pvt. Ltd. 180


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Step4: Element 7 is compared with element 8.
3 5 2 7 8 1 9 No change

Since 7 < 8, position of these elements need not be exchanged.


Step5: Element 8 is compared with element 1.
3 5 2 7 8 1 9

Since 8 > 1, their respective positions are exchanged, then the resulting series will be as shown below:
3 5 2 7 1 8 9

This is the end of iteration 2,8 is patched before the element 9.


3 5 2 7 1 8 9 Patching 8 to 9

Iteration 3
Step1: Element 3 is compared with element 5. As 3 < 5 the series remains the same.
3 5 2 7 1 8 9 No change

Step2: Element 5 is compared with element 2.


3 5 2 7 1 8 9

Since 5 > 2, exchange the position of element 5 with that of element 2. Then the resulting series will be as
shown below:
3 2 5 7 1 8 9

Step3: Element 5 is compared with element 7.


3 2 5 7 1 8 9 No Change

Since 5 < 7, there is no need of exchanging the positions.


Step4: Element 7 is compared with element 1.
3 2 5 7 1 8 9

Since 7 >1, exchange the position of element 7 with that of element 1. Then the resulting series will be as
shown below:
3 2 5 1 7 8 9

This is the end of iteration 3. The element 7 is patched before the element ‘8’.
3 2 5 1 7 8 9

Iteration 4
Step1: Element 3 is compared with element 2.
3 2 5 1 7 8 9

181 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Since 3 >2, exchange the position of element 3 with position of element 2. Then the resulting series will
be as shown below,
2 3 5 1 7 8 9

Step2: Element 3 is compared with element 5.


2 3 5 1 7 8 9
No change

Since 3 <5, there is no need of exchanging the positions of these elements.


Step3: Element 5 is compared with element 1.
2 3 5 1 7 8 9

Since 5 >1, exchange the position of element 5 with that of element 1. Then the resulting series will be as
shown below:
2 3 1 5 7 8 9

This is end of iteration 4. The element 5 is patched before element 7.


2 3 1 6 7 8 9

Iteration 5
Step1: Element 2 is compared with element 3.
5 9
2 3 1 7 8 No change

Since 2< 3, series remains the same.


Step2: Element 3 is compared with element 1.
2 3 1 5 7 8 9

Since 3 >1, exchange the position of element 3 with that of element 1. Then the resulting series will be as
shown below:
2 1 3 5 7 8 9

This is the end of iteration 5. The element 3 is patched before the element 5.
Iteration 6: Element 2 is compared with element 1.
2 1 3 5 7 8 9

Since 2 >1, exchange the position of element 2 with that of element 1. Then the resulting series will be as
shown below:
1 2 3 5 7 8 9

This is end of iteration 6. The element 2 is patched before the element 3.


Since, the only element left is 1, it is patched before 2.
Finally, the completely sorted list of elements obtained is given below:
1 2 3 5 7 8 9

Publishers and Distributors Pvt. Ltd. 182


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Step 3
4.1.3 Insertion Sort
Now, select the first element in the unsorted
Q29. Explain about Insertion sort.
list i.e., 36 and this will be the key element (i.e., key
May-18, Q8(b) [MGU]
element = 36).
OR
Key
Write a C++ program for insertion sort.
Show the steps of the insertion algorithm
for the list of data 76, 67, 36, 55, 23, 14, 6. 67 76 36 55 23 14 6
Nov./Dec.-18, Q12(a) [OU]
Sorted Unsorted
OR
Write a program code for insertion sort The key element i.e., 36 is compared with the
algorithm. Show the stepwise execution elements in the sorted list and placed it in appropriate
of the algorithm for the following list of position. Since, the key element 36 is less than both 67
data: 76, 67, 36, 55, 23, 14, 6. and 76 (i.e., 36 < 67 and 36 < 76). The element 36 will
(Model Paper-II, Q20 | Nov./Dec.-17, Q12(a) [OU]) be inserted before 67.
OR
36 67 76 55 23 14 6
Sort the given list of numbers 76, 67, 36,
55, 23, 14, 6 using insertion sort. Sorted Unsorted
(Refer Only Topic: Steps for Insertion Sorting)
Answer : Nov./Dec.-19, Q12(a)(i) [OU] Step 4
Insertion Sort Now, select the first element in the unsorted
Insertion sort is a technique list i.e., 55 and this will be the key element (i.e., key
in which an element is selected and element = 55).
placed in its appropriate position. Key
The list will be divided into two sub-
lists. i.e., sorted list and unsorted list. If I Don’t Come,
The first element is selected from the My Method Will Come 36 67 76 55 23 14 6
unsorted list, it is compared with all the elements in the
Sorted Unsorted
sorted list and then inserted in its appropriate position
in the sorted list. This process will be repeated until all The key element i.e., 55 is compared with the
the elements in the list are sorted. elements in the sorted list and placed it in appropriate
Steps for Insertion Sorting position.
Given list of data, Key
76, 67, 36, 55, 23, 14, 6
Step 1
The given list is divided into two sublists. The first 36 67 76 55 23 14 6
element is selected and placed before the unsorted list. Sorted Unsorted
76 67 36 55 23 14 6
The key element i.e., 55 is compared with 36,
Sorted 67, 76. Since, the key element 55 is greater than 36 and
Unsorted
lesser than 67 and 76 (i.e., 55 > 36 and 55 < 67, 55 <
Step 2 76). So, it is placed after the element 36. The list after
Now, select the first element from the unsorted insertion is as shown below,
list. Let this element be the key element (key = 67).
Key 36 55 67 76 23 14 6
Sorted Unsorted
76 67 36 55 23 14 6
Step 5
Sorted
Unsorted Now, select the first element in unsorted list and
The key element i.e., 67 is compared with the consider it as the new key (i.e., key element = 23).
element in the sorted list and place it in appropriate Key
position. Since, 76 > 67, 67 will be inserted before 76.
67 76 36 55 23 14 6 36 55 67 76 23 14 6
Sorted Unsorted Sorted Unsorted

183 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
The key element i.e., 23 is compared with the Program
all elements present in the sorted list i.e., 36, 55, 67, 76 #include <iostream.h>
and placed it in appropriate position. #include <conio.h>
Key #define MAX 10
class Inssort
36 55 67 76 23 14 6 {
Sorted Unsorted int arr[MAX],n;
public:
Since the key element is lesser than all the void getele( );
available elements in the sorted list (i.e., 23 < 36, 55, void showele( );
67, 76), it is inserted before 36. The list after insertion void sort( );
is as shown below, };
23 36 55 67 76 14 6 void Inssort :: getele( )
Sorted Unsorted {
cout<<“Enter number of elements :”;
Step 6 cin>>n;
Now, select the first element in the unsorted list cout<<“Enter elements for sorting:\n”;
and consider it as the new key (i.e., key element = 14). for(int i=0;i<n;i++)
Key cin>>arr[i];
}
23 36 55 67 76 14 6 void Inssort :: showele( )
{
Sorted Unsorted
cout<<“Display the sorted list of elements:\n”;
The key element i.e., 14 is compared with the for(int i=0;i<n;i++)
elements in the sorted list and placed it in appropriate cout<<arr[i]<<“ ”;
position. }
Key
void Inssort :: sort( )
{
int tmp,min;
23 36 55 67 76 14 6
for(int i=0;i<n;i++)
Sorted Unsorted {
tmp = arr[i];
The key element is compared with 23, 36,
for(int j=i;j>0 && arr[j – 1]>tmp;j– –)
55, 67, 76 and the key is lesser than all the elements
{
present in the sorted list,(i.e., 14 < 23, 36, 55, 67, 76).
arr[j] = arr[j–1];
So, place it before element 23. The list after insertion
}
is as shown below,
arr[j] = tmp;
14 23 36 55 67 76 6 }
Sorted Unsorted }
void main( )
Step 7 {
Now, select the only element that is present in clrscr( );
unsorted list and it is considered as the key element. cout<<“INSERTION SORT\n”;
Key
Inssort obj;
obj.getele( );
obj.sort( );
14 23 36 55 67 76 6
obj.showele( );
Sorted Unsorted getch( );
}
The key element i.e., 6 is compared with all
Output
the elements present in the sorted list. Since the key
element is lesser than all the element present in the
sorted list (i.e., 6 < 14, 23, 36, 55, 67, 76), it is placed
before element 14. Hence, the final sorted list is as
shown below,
6 14 23 36 55 67 76

Sorted List

Publishers and Distributors Pvt. Ltd. 184


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Algorithm Iteration 1
Step 1 : Set index variable, i=2 The list is scanned for the smallest element.
Step 2 : Repeat step 3 to step 9 until all the elements
76 67 36 55 23 14 6
in the list are sorted.
Step 3 : Set Key = List [i]
First Smallest
Step 4 : Set position to i
Step 5 : Repeat step 6 to step 8 while (position > 1) 6 is found to be smallest element and it is swapped
and(List[position – 1] > key) with the first element i.e., 76 in the unsorted list,
Step 6 : Move List [position-1] to List [position] 76 67 36 55 23 14 6
Step 7 : Move position-1 to position
Swap
Step 8 : Move key to List [position]
Unsorted
Step 9 : Increment i Sorted

Step10: End 6 67 36 55 23 14 76
Time Complexity
After swapping, the element 6 becomes sorted
The time complexities (i.e., worst case, average element.
case and the best case) of insertion sort are as shown in
the below table, Iteration 2

Case Time Complexity The unsorted portion of the list is scanned for the
smallest element.
Average case O(n2)
Best case n–1 6 67 36 55 23 14 76

Worst case O(n2)


First Smallest
4.1.4 Selection Sort The smallest element found is 14. Swap it with
Q30. Write about selection sort with an example. the first element i.e., 67
(Model Paper-I, Q20(b) | Nov./Dec.-19, Q10(b) [MGU]) 6 67 36 55 23 14 76
OR
Write a program code for selection sort Swap
algorithm. Show the stepwise execution
of the algorithm for the following list of The list after swapping is as follows,
data: 76,67,36,55,23,14,6. 6 14 36 55 23 67 76
Answer : May/June-18, Q12(b) [OU]
Sorted Unsorted
Selection Sort
Selection sort is one of the Iteration 3
simplest internal sorting technique.
The unsorted portion of the list is scanned for the
It involves selection of the smallest If I Don’t Come,
smallest element
element from the given list and My Method Will Come
replacing it with the first element. 6 14 36 55 23 67 76
This process is done on the unsorted portion of the list
and will be repeated until all the elements in the list First Smallest
are sorted. Initially the complete list will be unsorted.
The selected smallest element is swapped with the first The smallest element found is 23. Swap it with
element. Now, the first element is said to be sorted the first element i.e., 36
and the remaining elements are unsorted. This process 6 14 36 55 23 67 76
will be repeated on the unsorted portion until all the
elements in the list are sorted. Swap
Problem
The list after swapping is as follows,
The given list is 76,67,36,55,23,14,6
Consider the following unsorted list. 6 14 23 55 36 67 76
76 67 36 55 23 14 6 Sorted Unsorted

185 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Iteration 4 Iteration 7
The unsorted portion of the list is scanned for the Since, there is only one element in the unsorted
portion, it will automatically be placed in its proper place.
smallest element.
So there is no need of swapping.
6 14 23 55 36 67 76 The final sorted list is as follows,
6 14 23 36 55 67 76
First Smallest
Sorted
The smallest element found is 36. Swap it with Program
the first element i.e., 55
For answer refer Unit-IV, Page No. 186, Q.No.
6 14 23 55 36 67 76 31, Topic: Program.
Q31. Write algorithm, time complexity and
Swap
program for selection sort.
The list after swapping is as follows, Answer :
Algorithm for Selection Sort
6 14 23 36 55 67 76
Step 1 : Read all the elements from the list.
Sorted Unsorted Step 2 : Store each element in an array
Step 3 : Set the index value i=1
Iteration 5
Step 4 : Repeat step 5 to step 10 until all the elements
The unsorted portion of the list is scanned for the in the list are sorted.
smallest element. Step 5 : Set first to i
6 14 23 36 55 67 76 Step 6 : Set smallest to i+1
Step 7 : Repeat step 8 and step 9 while smallest <
First size_of_the_list.
Smallest Step 8 : If smallest < min, swap min and smallest.
Step 9 : Increment smallest
The smallest element found is 55. It has to be
swapped with the first element in the unsorted potion Step 10 : Increment i
of the list. But, 55 is found to be first element. So, there Step 11 : End
is no need of swapping and 55 is moved to the sorted Time Complexity
portion of the list. The time complexities (i.e., worst case, average,
case, best case) of selection sort are as shown in the
6 14 23 36 55 67 76 below table,

Sorted Unsorted Case Time Complexity


Average case O(n2)
Iteration 6
Best case O(n2)
The unsorted portion of the list is scanned for
Worst case O(n2)
the smallest element
Program
6 14 23 36 55 67 76 #include<iostream>
#include<conio.h>
First #define MAX 10
Smallest
using namespace std;
The smallest element found is 67. It has to be class selsort
swapped with the first element in the unsorted portion {
of the list. But, 67 is found to be first element. So, there int arr[MAX],n;
is no need of swapping and 67 is moved to the sorted
public:
portion of the list.
void getele( );
6 14 23 36 55 67 76 void showele( );
void sortele( );
Sorted Unsorted
};

Publishers and Distributors Pvt. Ltd. 186


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
void selsort :: getele( )
4.1.5 Quick Sort
{
Q32. Write about quick sort with an example.
cout<< “Enter the size of an array:”;
(Model Paper-III, Q19(a) | Nov./Dec.-19, Q10(a) [MGU])
cin>>n; OR
cout<< “Enter the elements of an array to be Write an algorithm for Quick sort. Explain
sorted:\n”; the step-by-step procedure of quick sort
for(int i=0;i<n;i++) on the list 25, 57, 48, 37, 12, 92, 86, 33
cin>>arr[i]; June/July-19, Q12(a) [OU]

} OR
Write an algorithm for quick sort. Show
void selsort :: showele( )
the stepwise execution of the algorithm
{ for the following list of data: 25, 57, 48,
cout<< “The array after performing selection 37, 12, 92, 86, 33.
sort is:\n”; Answer : Nov./Dec.-17, Q12(b) [OU]
for(int i=0;i<n;i++) Quick Sort
cout<<arr[i]<< “ ”; Quick sort is the most powerful sorting
algorithm. It uses the policy of
}
divide and conquer. It is also known
void selsort :: sortele( ) as partition exchange sort. Suppose,
{ there are ‘n’ elements in the list
ember me
int tmp,min; which are to be sorted. Quick sort Rem with concept
for(int i=0;i<n;i++) method divides the list into two
sublists based on an element called
{
pivot element or key. Usually, the first element in list
min=i; is the pivot element.
for(int j=i+1;j<n;j++) Consider ‘A’ as pivot element. Now, the elements
{ which are less than or equal to A are moved to left and the
if(arr[min] > arr[j]) elements which are greater than A are moved to its right.
Thus, now there are two sublists. A new pivot element is
{
identified in both list 1 and list 2. Again these sublists are
min=j; partitioned into further sublists and so on. This process
} continues until entire list gets sorted.
} Example
tmp = arr[min]; Given data is,
25, 57, 48, 37, 12, 92, 86, 33
arr[min] = arr[i];
Step 1
arr[i] = tmp;
25 57 48 37 12 92 86 33
}
} Key i j
int main( )
{ i and j are the first and last element of the list
respectively assume the first element as key.
selsort obj;
Compare key with i, j.
obj.getele( );
Step 2
obj.sortele( );
25 57 48 37 12 92 86 33
obj.showele( );
return 0;
} Key i j
Output as a[i] > a[key] then i stops incrementing.
Step 3
25 57 48 37 12 92 86 33

Key i j
as i> j swap i and j

187 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Step 4 Step 12
25 33 48 37 12 92 86 57 92 86 57

Key i j Key i j
as j is decremented as a[j] < a[key] swap a[j] with a[key]
Step 5 Step 13

25 33 48 37 12 92 86 57 57 86 92

Therefore, these elements are sorted.


Key i j \ The sorted elements are 12 33 37 48 57 86 92.
Compare key value with j and decrement j. Q33. Write algorithm and program for quick
sort.
Step 6
Answer :
25 33 48 37 12 92 86 57 Algorithm
One way to effect a partition efficiently is as
Key i j follows. Let x = a[lb] (where lb is lower bound) be
the element whose final position is to be decided. Two
as a[i] < a[key] swap a[j] with a [key] pointers left and right are initialized to lower and upper
Step 7 bounds of the list. At any point during execution, each
element in a position above left is greater than or equal
12 33 48 37 25 92 86 57
to x and each element in the position below right is less
than or equal to x. The two pointers left and right are
Key element moved towards each other in the following ways,
Step1: Repeatedly decrease the pointer right by one
Now, repeat the process on the elements at the position until x ≥ a [right]
left side of the key element.
Step2: Repeatedly increase the pointer left by one
Step 8 position until x ≤ a [left]
12 33 48 37 Step3: If a[left>a[right] then, interchange a [right]
with a [left]
Step4: If x>a [right] then interchange x and a [right]
Key i j
Step5: If x<a [left] then interchange x and a [left]
Consider key, i and j The process is repeated until the condition in
Step 9 step 3 fails ( when left>right), at which point x [right]
is interchanged with x[lb] , whose final position was
12 33 48 37 sought and j is set to left.
Program
Key i j #include<iostream>
Compare key value with i and j #include<conio.h>
using namespace std;
Step 10
class QuickSort
12 33 48 37 {
public:
Key i j int no_of_elements;
i > j swap i and j int elements[10];
public:
Step 11
void getarray( );
12 33 37 48
void sortit(int[ ], int, int);
Therefore, these elements are sorted. void partition(int[ ],int ,int,int&);
Now, repeat the process on the elements at the void display( );
right side of the key element. };

Publishers and Distributors Pvt. Ltd. 188


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
void QuickSort::getarray( ) int main( )
{ {
cout<< “Enter the size of an array:”;
QuickSort QS;
cin>>no_of_elements;
cout<< “Enter the elements of an array QS.getarray( );
to be sorted:\n”; cout<< “Sorting is given in step by step
for(int i=0;i<no_of_elements;i++) showing each iteration”<<endl;
{
QS.sortit(QS.elements,0,QS.
cin>>elements[i];
no_of_elements-1);
}
} QS.display( );
void QuickSort::sortit(int x[ ], int lb, int ub) return 0;
{
}
int j;
if(lb >= ub) Output
return;
display( );
partition(x,lb,ub,j);
sortit(x,lb,j–1);
sortit(x,j+1,ub);
} Q34. Explain how the complexity is calculated
void QuickSort::partition(int x[ ],int lb,int ub,int &pj) for the quick sort.
{
Answer :
int a, down, temp, up;
Quick Sort Efficiency
a = x[lb];
up = ub; Quick sort efficiency can be determined using
down = lb; a key. This is because the key can divide the given list
into two parts where it is possible that one part contains
while(down < up)
more elements than the other or it is even possible that
{
these partitions are not sorted.
while(x[down] <= a)
Consider two cases for analyzing the efficiency
down++;
of quick sort from comparison point of view.
while(x[up] > a)
Case 1
up– –;
if(down < up) Two important assumptions are made in this case are,
{ (i) Consider that the key equally divides the list
temp = x[down]; such that both partitions contain equal number
x[down] = x[up]; of elements in the middle.
x[up] = temp; (ii) The number of elements present in the list are
} represented using power of 2 i.e., if there are n
} elements in the array,
x[lb] = x[up]; then n = 2m ⇒ m = log2 n ... (1)
x[up] = a; In such scenario, n comparisons are made at 1st
pj = up; pass, n/2 comparisons are made at 2nd pass, and
} so on.
void QuickSort::display( ) ∴ Total number of comparisons
{ = O(n) + O(n) + ..... m terms
for(int i = 0; i < no_of_elements; i++) = O(n * m) ... (2)
{ From equation (1) m = log2 n
cout<<elements[i]<< “ ”;
Substituting it in equation (2),
}
cout<<endl; O(n log n)
} ∴ Quick sort efficiency = O(n log n)

189 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Case 2
In this case assume that, the key divides the list in two parts, where one part is empty with no element and
other part contains all the elements. This is the worst case.
Total number of comparisons
= (n – 1) + (n – 2) + ...... + 2 + 1
1
= (n – 1)* n
2
1 2 1
= (n ) – (n) = O(n2)
2 2
Therefore the worst case time complexity of quick sort is O(n2). Worst case occurs when the elements are
already in sorted order.

4.1.6 Merge Sort


Q35. Explain the merge sort technique and write a program for sorting the numbers in ascending
order using merge sort. Nov./Dec.-19, Q12(b) [OU]
OR
Explain and write an algorithm for merge sorting. Sort the elements using merge sort
38,52,13,60,42,13,41,78,85. (Model Paper-III, Q20 | Nov./Dec.-17, Q8(a) [MGU])
OR
Explain merge sort with example. May/June-19, Q8(a) [MGU]
OR
Write an algorithm for Merge Sort.
(Refer Only Topic: Algorithm)
Answer : May-18, Q8(a) [MGU]
I am Simple and Easy
Merge Sort
Merge sort is an external sorting algorithm which makes use of secondary storage. It uses divide and conquer
approach to sort a given list. It divides the list into n sublists of equal size until only one element is left in sublist. After
that it recursively applies merge sort on two sorted sublists to form a combined list. This merging process is repeated
until the final sorted list is obtained.
Example
The given list of elements are 38,52,13,60,42,13,41,78,85.
38 52 13 60 42 13 41 78 85

38 52 13 60 42 13 41 78 85

38 52 13 60 42 13 41 78 85

38 52 13 60 42 13 41 78 85

38 52

38 52 13 60 42 13 41 78 85

13 38 52
13 41 78 85

13 38 42 52 60

13 13 38 41 42 52 60 78 85

Publishers and Distributors Pvt. Ltd. 190


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Algorithm void array :: add (int num)
Step1: Read all the elements from the list. {
if (count < size)
Step2: Store each element in an array.
{
Step3: Initialize the location of first element = low and
a[count] = num ;
last element = high.
count++ ;
Step4: Divide the list into two sublists of equal size
}
using following formula,
else
low + high
mid = cout << “\nArray is full” << endl ;
2
Step5: Repeat step 4 until there is only one element }
remaining in the list. void array :: display( )
Step6: Compare each element in the sublist and sort {
them in ascending order. for ( int i = 0; i < count ; i++)
Step7: Merge the sorted sublist into single sorted list. cout << a[i] << “ ” ;
Step8: Repeat step 7 until the original sorted list is cout << endl;
obtained. }
Program void array :: merge_sort(int low,int high)
#include <iostream> {
#include<conio.h> int mid;
using namespace std; if(low<high)
const int MAX = 5; {
class array mid=(low+high)/2;
{ merge_sort(low,mid);
private: merge_sort(mid+1,high);
int *a; merge(low,mid,high);
int size; }
int count; }
public: void array :: merge(int low,int mid,int high)
array( ); {
array (int sz); int h,i,j,b[50],k;
void add (int num); h=low;
void display( ); i=low;
void merge_sort(int low,int high); j=mid+1;
void merge(int low,int mid,int high); while((h<=mid)&&(j<=high))
~array( ); {
}; if(a[h]<=a[j])
array :: array( ) {
{ b[i]=a[h];
count = size = 0; h++;
a = NULL; }
} else
array :: array(int sz) {
{ b[i]=a[j];
count = 0; j++;
size = sz; }
a = new int[sz] ; i++;
} }

191 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
if(h>mid) Space Complexity
{ Space complexity is the amount of memory
for(k=j;k<=high;k++) required by the algorithm to run. It can be computed
{ using the constant and instant characteristics. In
b[i]=a[k]; recursive methods, space is the major requirement for
i++; stack frame generated by recursive calls. Hence, the
} maximum amount of memory can be determined by
} the stack frame size and recursion depth:
else (i.e., size of stack frame * depth of recursion).
{
for(k=h;k<=mid;k++) In merge sort, the stack frame size remains
constant. The recursion depth is O[log(n)] . Therefore
{
the memory required for stack frames is O[log(n)]
b[i]=a[k];
i++; Each invocation has two temporary arrays, the
} size of which is similar to the number of positions to be
} sorted. At level x, the position would be px = n/2x. This
space is required after the invocation of recursive calls
for(k=low;k<=high;k++) a[k]=b[k];
and hence is allocated before making recursive calls.
}
The amount of space to be allocated is the sum of n/2x
array :: ~array( ) for j=0....log(n). This sum is equivalent to O(n) and is
{ less than 2*n. Hence, it can be concluded that space
delete a ; complexity of merge sort is O(n).
}
Q37. Explain, (i) Quick sort (ii) Merge sort.
int main( )
Give example.
{
array a(MAX) ; Answer : Nov./Dec.-18, Q8(b) [MGU]
a.add (11); (i) Quick Sort
a.add (2);
For answer refer Unit-IV, Page No. 187, Q.No. 32.
a.add (9);
a.add (13); (ii) Merge Sort
a.add (57); For answer refer Unit-IV, Page No. 190, Q.No. 35.
cout<< “------Merge sort-------\n” ;
a.merge_sort (0,4) ; 4.1.7 Comparison of Sorting Techniques
cout << “\nArray after sorting:” << endl ;
Q38. Discuss in brief about the following
a.display( ) ;
sorting techniques along with their
return 0;
advantages and disadvantages,
}
Output (i) Selection
(ii) Insertion
(iii) Bubble
(iv) Quick
(v) Merge.
Q36. What is time and space complexity for
merge sort? Answer :
Answer : (i) Selection Sort
Time Complexity Selection sort is an internal sorting technique
The time complexities of merge sort for average in which the smallest element is selected from
case, best case and worst is shown in table. the unsorted list and is placed at its appropriate
Cases Time Complexity position after swapping.
Average case O(n logn) Advantages
Worst case O(logn) 1. It is simple and easy to understand.
Best case O(n logn) 2. It requires very less exchanges.
Table: Time Complexities of Merge Sort 3. It requires very less iterations for sorting.

Publishers and Distributors Pvt. Ltd. 192


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Disadvantages Advantages
1. It consumes more memory space. 1. It is faster than the other techniques.
2. The performance degrades because of 2. It can be easily parallelized because of its
huge amount of data. divide-and-conquer nature.
3. It even sorts the sorted list, due to which 3. It does not requires temporary memory.
both time as well as memory space are
wasted. Disadvantages
(ii) Insertion Sort 1. It does not work well on the already
Insertion sort is a technique in which an element sorted lists or the list containing similar
is picked up and placed in its appropriate position elements.
in the list. This is done by initially dividing the 2. It swaps the elements which have same
list into two sublists i.e., sorted list and unsorted comparison keys.
list. An element is selected from the unsorted (v) Merge Sort
sublist and inserted in the correct position in the
Merge sort is a technique in which all the
sorted list. This process is repeated until all the
elements of the list are divided into individual
elements in the list are sorted.
elements initially and then merged by
Advantages simultaneously sorting them. This process is
1. It is efficient for small data set. repeated until all the elements are sorted and
2. It will not change the order of some keys merged.
in the list. Advantages
3. It consumes constant amount of extra 1. It can be applied on the list of any size.
memory space.
2. It merges the elements sequentially.
Disadvantages
1. It is not much efficient for a list with large 3. It is suitable for linked lists.
number of elements. Disadvantage
2. Performance degrades with the increase v It requires temporary memory space.
in the number of elements. Q39. Give the time complexities of various
(iii) Bubble Sort sorting techniques.
Bubble sort is a technique in which two adjacent Answer :
elements are compared and adjusted in a sorted
order. The largest element is bubbled up each time The time complexities of various sorting
when the end of the list is reached. This process techniques are as follows,
will be continued until all the elements in the list Selection Sort
are sorted and bubbled up.
The time complexities for best, average and
Advantages worst cases of selection sort are shown in the table
1. It is easy to understand and implement. below,
2. Performance increases if the list is already
a sorted list. Cases Time Complexity
3. It is efficient for less number of elements. Best Case O(n2)
Disadvantages Average Case O(n2)
1. It is relatively slower than other Worst Case O(n2)
techniques. Table: Time Complexities for Selection Sort
2. It consumes lot of time. Insertion Sort
3. It requires more number of iterations for a
The time complexities for best, average and
jumbled list.
worst cases of insertion sort are shown in the table be-
(iv) Quick Sort low,
Quick sort is a technique in which the list is
divided into two sublists based on the pivot Cases Time Complexity
element. One list consists of elements less than Best Case n–1
pivot element and another consists of elements Average Case O(n2)
greater than the pivot element. This process
Worst Case O(n2)
will be performed on each sublist until all the
elements in the list are sorted. Table: Time Complexities for Insertion Sort

193 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Bubble Sort Example
The time complexities of bubble sort i.e., worst
case, average case and best case are shown in the table
below,

Cases Time Complexity


Worst Case O(n2)
Average Case O(n2) Figure (1): Ascending Heap Tree
Best Case O(n2) The tree shown in figure (1) is an ascending
Table: Time Complexities of Bubble Sort tree because the content of each node is greater than its
parent.
Quick Sort
(ii) Descending Heap (Max Heap)
The time complexities of quick sort i.e., average
A descending heap of size ‘n’ can be defined as
case, best case and worst case are shown in the table
a complete binary tree of n nodes such that the content
below,
of each node is less than or `equal to its parent node.
Cases Time Complexity Example
Average case O(nlogn)
Worst case O(n2)
Best Case O(nlogn)

Table: Time Complexities of Quick Sort


Merge Sort
The time complexities of merge sort for average
case, best case and worst is shown in the table below,
Figure (2): Descending Heap Tree
Cases Time Complexity The tree in the figure (2) is a heap tree because
Average case O(n logn) the content of each node is less than its parent.
Worst case O(logn) Procedure for Maintaining the Heap Property
Best Case O(n logn) The heap property can be maintained by using a
procedure known as HEAPIFY (or MAX-HEAPIFY).
Table: Time Complexities of Merge Sort
The inputs to this procedure are an array (Arr) and an
4.2 Heaps index (ind). When this procedure is invoked, the binary
tree is formed at left (ind) and right (ind) is hepified.
4.2.1 Concept, Implementation Incase, if it does not satisfy the max-heap property i.e.,
if root node (i.e., Arr[ind]) is less than either left node
Q40. Define heap. Discuss a procedure for (i.e., Arr[left]) or right node (i.e., Arr[right]) then the
maintaining the heap property.
max-heap property is violated.
Answer : Model Paper-III, Q19(b) MAX-HEAPIFY (Arr, ind)
Heap left ← left (ind)
A complete binary tree in which the value node right ← right (ind)
is either greater than, lesser than or equal to values in if left ≤ heap-size [Arr] and A [left] > A[ind]
child nodes is called a heap.
then biggest ← left
Heap can be classified as, else biggest ← ind
(i) Ascending heap (min heap) if right ≤ heap-size [Arr] and Arr [right] >
(ii) Descending heap (max heap). Arr [biggest]

(i) Ascending Heap (Min Heap) then biggest ← right


if biggest ≠ ind
An ascending heap of size ‘n’ can be defined as
a complete binary tree of n nodes such that the content Then swap Arr [ind] ↔ [A biggest]
of each node is greater than or equal to its parent node. Max-HEAPIFY (Arr, Biggest).

Publishers and Distributors Pvt. Ltd. 194


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Initially, this procedure takes the biggest child Consider the below heap,
among the left and right child. After taking the biggest
8
child, it compares with the parent node (i.e., root node).
If the parent node is smaller than the biggest child, they
both are swapped. Otherwise, the procedure ends. In this
7 3
way, the largest key is placed at the root node. But, this
swapping might lead to violation of max-heap property
at its subtree. So, the max-heap procedure need to be 5 1 2

invoked again inorder to make the whole tree a heap. Figure: Heap
Q41. What are the properties that binary heap
The above heap can be represented in the form
must satisfy?
of array as shown below,
Answer :
Index 0 1 2 3 4 5 6 7
The two properties that a binary heap tree must
satisfy are as follows, Data 8 7 3 5 1 2
(a) Structure Property In the above illustrated array, the parent node
which is at the index is said to be at index (i – 1/2). The
(i) If the height of the binary tree is ‘h’ and contains
left child of the node at index is said to be at index 2 ×
2h+1 – 1 nodes them it is said to be complete. This
i +1. The right child at index i is said to be at index 2 ×
tree will be called as complete binary tree.
i +2.
(ii) A complete binary tree with height ‘h’ must satisfy
any one of the following conditions, As shown in the above figure, the node with value
7 will be at first location. The parent of it i.e., 8 will be at
v A binary tree is empty. 0th location. The left child 5 is at 2 × 1 +1 i.e 3rd location
v The left subtree of binary tree should be and the right child 1, is at 2 × 1+2 i.e., at 4th location.
complete (i.e., h – 1) and the right subtree Consider the below heap tree that is in its logical form,
should be completely full (i.e., h – 2).
57
v The left subtree of binary tree should be
completely full (i.e., h – 1) and the right
subtree should be complete (i.e., h – 1).
(iii) A complete binary tree is filled from left to right 36 11
incase if,
v Either all the leaf nodes are present on the
same level or every two nodes are adjacent 25 1 3 6
to each other.
v Each node present at the bottom level must Figure: Heap Tree
be far away from left side.
The above tree can be represented using an array
(b) Heap-order Property by applying the above define rules.
A binary tree fulfills the heap property when it
satisfy the following, Index 0 1 2 3 4 5 6
v A binary tree is empty. Data 57 36 11 25 1 3 9
v Each root node of a binary tree will be larger
4.2.2 Abstract Data Type
than its children as well as left subtree and
right subtree. Q43. Discuss about Heap ADT.
Q42. Explain the implementation of heap. Answer :
Answer : Heap ADT
Implementation of heap using array is simple, A binary tree which is complete and satisfies
easy and understandable. Heap needs the nodes to be the heap order property is called as Heap. The basic
numbered from top to bottom. In every level, the nodes operations that are performed on it are insert, delete,
must be numbered from left to right. The nodes are stored max-heap and min-heap. The class definition for heap
in the array at respective positions such as ith node is ADT is as follows,
placed at ith location in the array For example, the root class Node
will be placed at index 0 and its left child will be placed {
at index 1. int Arr[max];

195 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
int x; (i) Inserting 10
};
class Heap
{ (ii) Inserting 12
private:
Node *Root;
void ReHeapUp(int i);
void ReHeapDown(int i);
public:
Heap( ) (iii) Inserting 1
{
for(int i = 0; i<Max; i++)
Arr[i] = 0;
}
void Create( ); (iv) Inserting 14
void Insert(int n);
void DeleteMaxVal( );
};
ADT Operations
1. Create
The create( ) function is used to create a heap.
(v) Inserting 6
The keys that are in unordered manner and extracted one
at a time and then added to heap. With this the size of
the heap grows. For example, if ith key is added to the
heap that is already available with size i – 1, then the
heap size would be i. This is done in order to satisfy the
constraints. The ki value is compared with parent keys
value. If ki is found to be greater than the newly added (vi) Inserting 5
value then they both swap with each other.
This process repeats for each addition of new node.
The finally obtained tree would be heap tree with size i.
Algorithm
Step-1: Begin
Step-2: set s = i (vii) Inserting 7
Step-3: Search for the parent node of i in array
parent = (s – 1)/ 2
Step-4: Initialize the array
key[s] = newnode
Step-5: Insert the next node by heapifying the tree
while (s > = 0 & & key[parent] < = key[s]) void Heap : : create( )
5.1 Swap the parent with the child node {
tmp = key[parent]
int i, n, info;
key[parent] = key[s]
key[s] = tmp cout<<“\n Enter the number of element:”;
5.2 s = parent cin>>n;
5.3 parent = (s – 1)/ 2 cout<<“\n Enter info:”;
5.4 end. for (i = 0; i < n; i++);
Step-6: End {
This algorithm is called for every addition of a cin >> info;
new element into heap tree.
insert(info);
Example
Create a heap tree with elements 10, 12, 1, 14, 6, }
5, 7 }

Publishers and Distributors Pvt. Ltd. 196


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
2. Insert
Insertion of a new node can be done into the heap tree that is already built. Insertion is done using insert(Heap,
Data) method.
Consider a heap with ‘n’ number of elements. Assume ‘x’ as an element to be inserted. Before inserting,
initially a hole must be created in the position (n + 1). Now, check for the heap property whether it gets violated
when x is placed into that hole. If heap property does not get violated then it means that it is the right position for
‘x’. But, if the heap property gets violated, then perform the operation “push-up” or “percolate-up” for ‘x’. This
process is continued until the heap property is achieved. This can be performed by sliding the element present in
the holes into the parent node hole by bubbling the hole up towards the root. This process is continued until ‘x’
occupies the hole.
If ‘h’ is the heap height, then O(h) represents the worst case complexity of insert operation and O(logn)
represents the insertions.
Example
Consider the following heap in which the element 3 is to be inserted.

3. Delete
Deleting the maximum element from the list is to remove the root (since root is the maximum value) from
the tree. With this the tree will be without the root, thus the heap need to be reconstructed. The data that is in the
last heap node to the root is moved into root by performing reheapDown. Consider the below heap tree,
70 Node to be deleted

59 24

48 1 15 11

37
Figure: Heap Tree
The top element of the tree is deleted by using DeleteMaxVal(Heap) method. When the value 70 is deleted,
then the last node value i.e., 37 is moved to root. The heap needs to be reconstructed through reheapDown. The
below shown is the heap tree reconstructed after deletion.

197 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Example
59
void Heap : : ReHeapDown(int i)
{
int tmp;
48 24 while(2 * i < n)
{
j = 2 * i + 1;
37 1 15 11 if (j + 1 < n && arr [j + 1] > arr[j])
Reheap Up j = j + 1;
if(arr[i] > arr[j])
Whenever an element is to be inserted into a given
break;
heap, reheap up operation is performed.
else
Algorithm
{
reheapUp (heap, begin)
tmp = arr[i];
If(begin > 1)
arr[i] = arr[j];
set parent = begin/2 arr[j] = tmp;
if (heap [parent] < heap [begin]) i = j;
set temp = heap [begin] }
set heap [begin] = heap [parent] }
set heap [parent] = temp }
call reheapUp (heap, parent) void Heap : : Delete_MaxVal( )
End if {
End if int tmp;
End tmp = arr[0];
Example arr[0] = arr[n – 1];
void Heap : : ReHeapUp(int i) arr[n – 1] = tmp;
{ ReHeapDown(0);
int tmp; }
/
while(i > 0 and arr[i] > arr[i – 1] 2]
4.2.3 Heap Sort
{
tmp = arr[i]; Q44. Explain Heap sort with example.
(Model Paper-II, Q19 | May/June-19, Q8(b) [MGU])
a [i] = arr[(i – 1)/2];
a[(i – 1)/2] = tmp; OR
i = i/2; Write an algorithm for heap sort.
} (Refer Only Topic: Heap Sorting)
}
Answer :
Don’t Think
Nov./Dec.-17, Q8(b) [MGU] I am Complex
void Heap : : Insert(int p)
Heap Sorting
{
Heap sorting can be performed
arr[n] = p;
in two phases. They are as follows,
RetHeapup(n);
1. Construct heap
}
2. Sort heap.
ReheapDown 1. Construct Heap
Whenever an element is to be deleted from the In this phase, an array based list is transformed into
given heap, reheap down operation is performed. a heap. The array based list can be viewed as a binary
Algorithm tree, in which a binary tree would be called a heap if
1. Initially, variable is assigned with the value of each node in it is greater than or equal to its left and
the root node. right children.
2. The final element in the heap is stored at root Algorithm (Construct Heap)
position. Step1: Consider a heap tree which is empty. Begin at the
3. The heap size is decremented by one. first step,
4. The tree is reconstructed by applying reheap down i=1
operation from the root node. while (i < = n) do

Publishers and Distributors Pvt. Ltd. 198


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Step2: Repeat step 2 for all the elements swap (Arr[j], Arr[left])
Step2.1: Select the ith element from list and add j = left
an element to the ith place in array
else
n = Arr[i]
Arr1[i] = n If (Arr1[j] £ Arr[right])
j=i swap (Arr1[j], Arr1[right])
Step2.2: Repeat step 2.2 to step 2.3 until the j = right
root is checked Else
If Arr[j] > Arr1[j/2] then
flag = FALSE
tmp = Arr1[j]
End If
Arr1[j] = Arr1[j/2]
Arr1[j/2] = tmp End If
j = j/2 End If.
else Step3.2.4: If (left £ i) then
j=1 If (Arr1[j] £ Arr1[left]) then
End If
swap (Arr1[j], Arr1[left])
Step2.3: End while
j = left
i = i +1
Step2.4 : End while else
Step3: Stop flag = FALSE
2. Sort Heap End If
In this phase, the given heap is sorted. Note that, End If
the root node of heap (i.e., the first element of the list)
will be the largest element in the tree or list. Step3. 2. 5: End while
Algorithm Step4: End for loop
Step1: Read all the elements and store them in the array. Step 5: Stop
Step2: ConstructHeap (Arr) Example
Step3: Repeat this step for n – 1 times
Consider the following list,
Step3.1: Remove the root element and swap it
with the ith element.
tmp = Arr[i]
Arr1[i] = Arr1[1] Constructing Heap
Arr1[1] = tmp The first step of heap sort algorithm is to construct
Step3.2: Pre build the heap a heap. For doing this, we consider three pointers i, lc
and rc are considered, where ‘i’ points to a particular
Step3.2.1: Cannot build heap with one element
parent node, lc and rc points to its left and right child
in the tree
respectively.
If (i=1) then
Initially, i = (SizeofList/2) –1
exit
= (7/2) – 1
Step3.2.2: Begin at the root node
j=1 = 2
flag = TRUE left child (lc) = (2 * i) + 1
while (flag =TRUE) do = (2 * 2) + 1 = 5
left = 2* j right child (rc) = (2 * i) + 2
right = 2*j +1 = (2 * 2) + 2 = 6
Step3.2.3: Check whether the right is in the range
of heap and check whether left or right
will move up or not.
If (right £ i) then
If (Arr1[j] £ Arr1[ left]) AND
(Arr1[left] ³ Arr1[right]) then

199 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Now, the child elements pointed by lc and rc This results in the following list,
(i.e., 11 and 30) are compared with each other and find
the largest of them. Since, 30 > 11, the largest element
is 30. Then, compare the largest child element (i.e., 30)
with the parent element pointed by i (i.e., 15). Since, 15
is less than 30, swap 15 and 30 (i.e., swap the elements
pointed by ‘i’ and ‘rc’).
In the next iteration, swap the root node with
the last element (i.e., myList [5]) of list “myList[0] ...
myList[5]”.

This results in the following list,

This results in the following list,

In the next iteration, decrement ‘i’. And again


determine new ‘lc’ and ‘rc’ to heapify the tree. The same
process is repeated until the complete tree is heapified. Again, leave the last element i.e., List[5] and
The final heap tree obtained is as follows, construct the heap from the remaining list i.e., “myList[0]
... myList[4]”. This results in the following list.

Figure: A Heap List and its Corresponding Heap Tree


In the next iteration, swap the root node with last
Sorting Heap element of list “myList[0] ... myList[4]”.
The root node in the given heap, is the largest
node in the list. Swap it with the last node of this list.

This results in,

This result in,

Again, the last element i.e, List[4] is at its proper


place, therefore, leave it and construct heap from the
Now, leave the last element i.e., 30. Since, it remaining list i.e., “myList[0] ... myList[3]”. This results in,
got to its proper place and the remaining elements of
the list are adjusted to make them heap again. This is
done by constructing a heap from the list “myList[0] ....
myList[5]”.
Note that, here the last element i.e., myList[6] is
not considered. Swap the root with last element i.e., List[3].

Publishers and Distributors Pvt. Ltd. 200


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III

This results in,

Leave the last element i.e., 9 and restore heap from the list “myList[0] ... myList[2]”.

Now, swap root node with last element i.e., List[2] = 3.

This results in,

Now, leave the last element i.e., myList[2] and restore the heap from the list “myList[0] ... myList[1]”

Then, again swap the root node with last element.

201 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
This results in the following list.

Leave the last element i.e., myList[1] and restore the heap. Since, the heap has only one element it is already
a heap. Hence the whole list is sorted.

Q45. Explain the step-by-step procedure to construct a heap tree using the list of keys.
8, 20, 9, 4, 15, 10, 7, 22, 3, 12.
Answer : Nov./Dec.-18, Q12(b) [OU]

Given list of keys are,


8, 20, 9, 4, 15, 10, 7, 22, 3, 12
Construction of a Heap Tree
Step 1
If I Don’t Come,
Insert the first element i.e., 8 as the root in the heap tree. My Method Will Come

Step 2
Now, insert the next element i.e., 20 as the left child into the heap tree.

Swap 8

20

Since, the element 20 > 8, swap both the elements, i.e., 8 and 20.

20

Step 3
Now, insert the next element i.e., 9 into the heap tree as the right child to root node 20.

20

8 9

Publishers and Distributors Pvt. Ltd. 202


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
Step 4 Step 7
Now, insert 4 as the left child to the node 8 in the Now, insert 7 as the right child the node 10 in the
heap tree. heap tree.
20
20

15 10
8 9
4 8 9 7

4 Step 8
Now, insert 22 as the left child to the node 4 in
Step 5 the heap tree.
Now, insert 15 as the right child to the node 8 in 20

the heap tree.


15 10
20

Swap 4 8 9 7
8 9
Swap 22

4 15 Since, 22 > 4, swap both the elements (i.e., 22 and 4).


20
Since, the element 15 > 8, swap both the elements
i.e., 15 and 8.
15 10
ap
Sw

20

22 8 9 7
15 9

4
4 8
Now again 22 > 15, so swap both of the elements
(i.e., 22 and 15).
Step 6
Swap 20
Now, insert 10 as the left child to node 9 in the
heap tree.
22 10
20
15 8 9 7

15 9
4
Swap
4 8 10 Swap, 20 and 22, as the node 22 is greater than
the root node 20.
Since, 10 > 9, swap both the elements i.e., 9 and 10. 22

20
20 10

15 10
15 8 9 7

4 8 9 4

203 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++
Step 9 friend void create_heap(heap &);
Now, insert 3 as the right child to the node 15. friend void sort_heap(heap &);
void showele(void);
22
};
void heap :: getele(void)
20 10
{
15 9 7
cout<< “Enter required size of the Array :”;
8
cin>>size;
4 3
cout<< “\nEnter the “<<size<< “ Elements\n”;
for(int i=1;i<=size;i++)
Step 10 cin>>k[i];
Now, insert the last element ‘12’, as the left child }
to the node 8. void heap :: showele(void)
22 {

20 10 cout<< “\nHeap Function Output”<<endl;


for(int i=1;i<=size;i++)
cout<<k[i]<< “ ”;
15 8 9 7
}
Swap void create_heap(heap &a)
4 3 12 {
int q,i,j,key;
Since 12 > 8, swap both of them. Finally, the
for(q=2;q<=a.size;q++)
heap constructed is as shown below,
{
22
i=q;
key=a.k[i];
20 10
j=i/2;
while(i>1 && key>a.k[j])
15 12 9 7
{
a.k[i]=a.k[j];
4 3 8 i=j;
j=i/2;
Q46. Write a C++ program for heap sort. if(j<1)
Answer : j=1;
Program }
#include <iostream> a.k[i]=key;
#include <conio.h> }
using namespace std; }
void sort_heap(heap &a)
class heap
{
{
int q,i,j,key,tmp;
int k[11],size; for(q=a.size;q>=1;q--)
public: {
void getele(void); tmp=a.k[1];

Publishers and Distributors Pvt. Ltd. 204


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
a.k[1]=a.k[q];
a.k[q]=tmp;
i=1;
key=a.k[i];
j=2*i;
if(j+1 < q)
{
if(a.k[j+1] > a.k[j])
j++;
}
while(j<=q-1 && key<a.k[j])
{
a.k[i]=a.k[j];
i=j;
j=2*i;
if(j+1 < q)
{
if(a.k[j+1] > a.k[j])
j++;
}
else break;
}
a.k[i]=key;
}
}
int main( )
{
heap o1;
o1.getele();
create_heap(o1);
sort_heap(o1);
o1.showele( );
return 0;
}
Output

205 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

EXERCIsE AND PRACTICE QUEsTIoNs

Short Questions

1. Explain linear search. (Refer Q2) May/June-19, Q4 [MGU]

2. Explain the sequential search algorithm with an example. (Refer Q4) Nov./Dec.-17, Q7 [OU]
3. Write a program for sequential search. (Refer Q5) Nov./Dec.-19, Q7 [OU]
4. List the advantages and disadvantages of binary search. (Refer Q6) Nov./Dec.-19, Q6 [MGU]
OR
What are the Pros of binary search? (Refer Q6) Nov./Dec.-18, Q7 [OU]
5. Define internal and external sorting. (Refer Q10) June/July-19, Q7 [OU]
6. Apply the bubble sort algorithm to sort the list of data:
2,10,6,4,8. (Refer Q11) May/June-18, Q7 [OU]
7. Sort the elements using quicksort: 52,38,81,22,48,13,69,93. (Refer Q13) Nov./Dec.-17, Q4 [MGU]
8. Rearrange following numbers using quick sort.
10,6,3,7,17,26,56,32,72. (Refer Q14) May-18, Q4 [MGU]
9. Define a heap with an example. (Refer Q16) June/July-19, Q8 [OU]
OR
Define a heap. Build the heap tree for the list of data. (Refer Q16) Nov./Dec.-17, Q8 [OU]
10. What is heap? Explain heap construction process? (Refer Q17) Nov./Dec.-19, Q8 [OU]
11. Explain the concepts of min-heap and max-heap with
examples. (Refer Q18) May/June-18, Q8 [OU]
OR
Define minheap and maxheap with examples. (Refer Q18) Nov./Dec.-18, Q8 [OU]
12. What is heap Abstract Data Type? (Refer Q19) Nov./Dec.-18, Q4 [MGU]

Essay Questions
13. Explain different searching techniques with example. (Refer Q21) Nov./Dec.-18, Q8(a) [MGU]

OR
Write the binary search algorithm and trace the steps followed
to find 88 in the following list 8,12,24,28,32,45,48,51,56,62. (Refer Q21) May/June-18, Q12(a) [OU]
OR
Discuss Binary Search algorithm with an example. Write down the
Pros and Cons of binary search method. (Refer Q21) June/July-19, Q12(b) [OU]

14. Write a program for sorting the numbers in ascending order


using bubble sort. (Refer Q27) Nov./Dec.-19, Q12(a)(ii) [OU]

15. Explain about Insertion sort. (Refer Q29) May-18, Q8(b) [MGU]

OR
Write a C++ program for insertion sort. Show the steps of the insertion
algorithm for the list of data 76, 67, 36, 55, 23, 14, 6. (Refer Q29) Nov./Dec.-18, Q12(a) [OU]

OR
Write a program code for insertion sort algorithm. Show the
stepwise execution of the algorithm for the following list of data:
76, 67, 36, 55, 23, 14, 6. (Refer Q29) Nov./Dec.-17, Q12(a) [OU]

Publishers and Distributors Pvt. Ltd. 206


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III
16. Write about selection sort with an example. (Refer Q30) Nov./Dec.-19, Q10(b) [MGU]

OR
Write a program code for selection sort algorithm. Show the
stepwise execution of the algorithm for the following list of data:
76,67,36,55,23,14,6. (Refer Q30) May/June-18, Q12(b) [OU]

17. Write about quick sort with an example. (Refer Q32) Nov./Dec.-19, Q10(a) [MGU]

OR
Write an algorithm for Quick sort. Explain the step-by-step procedure
of quick sort on the list 25, 57, 48, 37, 12, 92, 86, 33 (Refer Q30) June/July-19, Q12(a) [OU]

OR
Write an algorithm for quick sort. Show the stepwise execution
of the algorithm for the following list of data:
25, 57, 48, 37, 12, 92, 86, 33. (Refer Q32) Nov./Dec.-17, Q12(b) [OU]

18. Explain the merge sort technique and write a program for
sorting the numbers in ascending order using merge sort. (Refer Q35) Nov./Dec.-19, Q12(b) [OU]
OR
Explain and write an algorithm for merge sorting. Sort the
elements using merge sort 38,52,13,60,42,13,41,78,85. (Refer Q35) Nov./Dec.-17, Q8(a) [MGU]

OR
Explain merge sort with example. (Refer Q35) May/June-19, Q8(a) [MGU]

OR
Write an algorithm for Merge Sort. (Refer Q35) May-18, Q8(a) [MGU]

19. Explain, (i) Quick sort (ii) Merge sort. Give example. (Refer Q37) Nov./Dec.-18, Q8(b) [MGU]

20. Explain Heap sort with example. (Refer Q44) May/June-19, Q8(b) [MGU]

OR
Write an algorithm for heap sort. (Refer Q44) Nov./Dec.-17, Q8(b) [MGU]

21. Explain the step-by-step procedure to construct a heap tree


using the list of keys.

8, 20, 9, 4, 15, 10, 7, 22, 3, 12. (Refer Q45) Nov./Dec.-18, Q12(b) [OU]

207 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

INTERNAL AssEssMENT/EXAM

I Multiple Choice
1. Time complexity of binary search is _______. [ ]
(a) log n (b) O(log n)
(c) O(n) (d) O(log n/log n 2)
2. A searching technique that works on unordered list _______. [ ]
(a) Linear search (b) Binary search
(c) Fibonacci search (d) None of the above
3. When does the worst case occur in linear search algorithm ________. [ ]
(a) If the key element lies somewhere in the middle of the array
(b) If the key element is not present in the array
(c) If the key element is located in the first position of the array
(d) If the key element lies at last of the array
4. When an element is found at the first position of the array during the search operation then it has the
time complexity? [ ]
(a) Best case (b) Average case
(c) Worst case (d) None of the above
5. Heap sort belongs to the family of sorting by _______. [ ]
(a) Selection (b) Insertion
(c) Exchange (d) Distribution
6. Which of the following is unstable sort? [ ]
(a) Bubble sort (b) Insertion sort
(c) Quick sort (d) Merge sort
7. The worst case time complexity of quick sort is _______. [ ]
(a) O(n) (b) O(n2)
(c) O(n3) (d) O(nlog n)
8. The sorting process of this algorithm is based on the pivot element _______. [ ]
(a) Selection sort (b) Insertion sort
(c) Quick sort (d) Radix sort
9. _____ is the most powerful sorting algorithm. It uses the policy of divide and conquer. [ ]
(a) Bubble sort (b) Insertion sort
(c) Merge sort (d) Quick sort
10. _____ sort splits the elements into partitions, so that only the current partition (on which we are working)
in main memory is reserved and the rest of the partitions can be stored on the external storage. [ ]
(a) Bubble sort (b) Insertion sort
(c) Merge sort (d) Quick sort

Publishers and Distributors Pvt. Ltd. 208


UNIT-4: Searching and Sorting, Heaps Computer Science Paper-III

II Fill in the Blanks


1. _____ is also called as sequential search.

2. Time complexity of linear search is _____.

3. _____ is a technique of organising data.

4. Sorting techniques are generally classified into ______ and _____ sorting.

5. If all the data is to be sorted can be accommodated at a time in memory is called _____ sorting.

6. The average case complexity of selection sort _____.

7. Time complexity of quick sort in the best case is _____.

8. Heap sort is an _____ sorting algorithm.

9. External sorting consists of two phases the _____ and the merge phase.

10. Time complexity of insertion sort is _____.

KEY
I. Multiple Choice
1. (d) 2. (a) 3. (d) 4. (a) 5. (a)

6. (c) 7. (b) 8. (c) 9. (d) 10. (c)

II. Fill in the Blanks


1. Linear search

2. O(n)

3. Sorting

4. Internal, External

5. Internal

6. O(n2)

7. O(n log n)

8. Unstable

9. Sort phase

10. O(n2)

209 Publishers and Distributors Pvt. Ltd.


Computer Science Paper-III Data Structures Using C++

III Very Short Questions and Answers


Q1. What is searching?
Answer :
Searching is a process of finding the correct location of an element from a list or array of elements.

Q2. What is selection sort?


Answer :
Selection sort is an internal sorting technique in which the smallest element is selected from the unsorted
list and is placed at its appropriate position after swapping.

Q3. Define Quicksort.


Answer :

Quick sort is a technique in which the list is divided into two sublists based on the pivot element. One list
consists of elements less than pivot element and another consists of elements greater than the pivot element. This
process will be performed on each sublist until all the elements in the list are sorted.

Q4. What are the time complexities of bubble sort?


Answer :
The time complexities of bubble sort i.e., worst case, average case and best case are shown in the table
below,

Case Time Complexity


Worst Case O(n2)
Average Case O(n2)
Best Case O(n2)

Q5. Define heap.


Answer :

A complete binary tree in which the value node is either greater than, lesser than or equal to values in child
nodes is called a heap.

Publishers and Distributors Pvt. Ltd. 210

You might also like