Cs 3rd Semester
Cs 3rd Semester
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.
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.
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
(i) A + B × (C + D) / F + D × E
A + B * (C + D) / F + D * E is ABCD + * F / + DE * +.
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
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.
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 ?
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.
Start
Read a, b, c
Stop
class array {
Very Sim
ex
pl
{ a[i+1]=a[i];
m
Co
t
g n
bu
ki
private: }
o
Lo
.
.
.
.
.
.
.
.
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]
1
push 1
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
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( )
main( )
P ends
Short Questions
1. Define data structure and describe the types of data structure. (Refer Q1) Nov./Dec.-19, Q1 [OU]
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]
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]
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]
Essay Questions
15. Briefly describe about the various types of data structure. (Refer Q22) Nov./Dec.-17,Q9(a)(i) [OU]
18. Explain in detail about how Algorithms are analyzed. (Refer Q30) Nov./Dec.-19, Q7(a) [MGU]
19. Define ADT for the “Integer” and explain all its functions and
axioms in detail. (Refer Q32) Nov./Dec.-18, Q9(a) [OU]
(ii) To delete an element at a given position. (Refer Q34) Nov./Dec.-18, Q9(b) [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]
(ii) Different types of data structures. (Refer Q38) Nov./Dec.-17, Q5(a) [MGU]
OR
24. What is an array? Explain about different types of arrays. (Refer Q40) May-18, Q5(a) [MGU])
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
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]
31. Describe about infix, postfix, prefix notations. (Refer Q53) Nov./Dec.-17, Q5(b)(i) [MGU]
35. Reverse the string “ABCDEF” using stack. (Refer Q65) Nov./Dec.-17, Q9(b)(ii) [OU]
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
2. A data structure in which all the data elements are stored in sequential manner is called _____
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 _____.
KEY
I. Multiple Choice
1. (c) 2. (b) 3. (d) 4. (d) 5. (c)
3. Two-dimensional
4. One-dimensional array
5. String
7. Top
8. Sequential manner
9. Flowchart
10. Algorithm
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.
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.
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
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]
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]
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])
Figure: Node
L R
NULL 10 20 30 NULL
Q17. What are the advantages of circularly list over single linked list?
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.
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
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.
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:
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.
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.
Front Rear
Primitive Operations
The basic operations performed on queues are in- front = –1,
sertion and deletion. rear = 2
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); {
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
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
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 2000
temp temp1
To link these two nodes, the link part of temp is made to point to temp1.
HEADER 1000 2000
1000 2000
temp
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.
2 3 4 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
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
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;
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”;
{ 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;
Head
5 10 15
Short Questions
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]
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]
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]
Essay Questions
15. What is recursion and write an example for recursion? (Refer Q21) Nov./Dec.-19, Q10(a)(i) [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]
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]
25. What is queue? And explain about circular queue and double
ended queue. (Refer Q40) Nov./Dec.-19, Q10(a)(ii) [OU]
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]
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]
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]
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
3. In this list, for any node N, N → rlink → llink is the address of the node N itself. [ ]
5. A _____ list allows traversal of the list in forward direction, but not in backward direction. [ ]
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
3. Types of linked list are _____, _____ and _____ linked lists
4. In _____ list, the last node link points to the first node of the list.
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.
KEY
I. Multiple Choice
1. Recursive function
4. Circular linked
5. Underflow
6. Priority queue
8. Garbage collection
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.
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.
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
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
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
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.
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.
B C
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
Step 6
Step 2
Step 3
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
1 2 3
A E C
Answer : Nov./Dec.-18, Q6 [OU]
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
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
D Data
B Link
Tag of 1
Link (next)
C (down)
B D F I H J
E
G
C
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
2 3 – –
Null
4 – – 5 – links
6 – –
Figure (2): An Example of Linked Representation of a Tree using Fixed Length Node
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.
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,
B C Level 1
D E F G Level 2
H I Level 3
2 3
2 3
4 5 6 7 8
4 5 6 7
Figure: Tree
B D
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.
return.
Example B
D
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)
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
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
8 4 2 3 5 RST RST
RST 2 RST 4 RST 8
8 4 2 3 5 7 12 9 10 14 3 2 7 5 4 RST 9 RST 12 8
2 3 4 5 RST 8 RST
Figure: Inorder Tree Traversal (LNR)
LST RST 8
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).
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.
Step 2: Insert 47 57
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
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.
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.
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.
Example 2 Example
1 2
4 3
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
[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
(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
1 8
8
5
6
2
4 2
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
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
3
6 8
1
5
2
4
(c) (d)
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
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.
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
t
Figure (2): Choose e1 = BC
ng
bu
i
Step-4
(ii)
Figure: Graph
The connected components of the above graph are,
(iii)
(iv)
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.
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]
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 Double Hashing After Inserting The resultant hash table for the keys given above
{89, 18, 49, 58, 69} will be,
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]
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]
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]
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]
INTERNAL AssEssMENT/EXAM
I Multiple Choice
1. A tree node that has no children is called a ______ node. [ ]
2. A node that is neither the root nor a leaf node is called as ______. [ ]
3. A binary tree which contains only the left child nodes or only the right child nodes is called as
______. [ ]
2. The average and worst-case time taken to perform operations on balanced binary tree with n node is
_____.
6. The two algorithms that are used to find minimum spanning tree are _____ and _____.
8. _____ is a technique that makes use of a hash function for mapping pairs to the corresponding (entries)
positions in a hash table
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)
2. O(log n)
4. Directed graph
5. Edges
7. Kruskal’s algorithm
8. Hashing
9. Linear probing
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’.
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.
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.
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.
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.
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.
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
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]
4 10 5 15 6 30 40 9 7
i=0
i=1
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
52 38 81 22 48 13 69 93
2 4 6 8 10
Key i j
Key i j 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])
Key i j
9 7
56 32 72
Insert 6
2
Key i j
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
};
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
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
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.
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]
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.
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
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.
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
Since 8 > 1, their respective positions are exchanged, then the resulting series will be as shown below:
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
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
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
Iteration 5
Step1: Element 2 is compared with element 3.
5 9
2 3 1 7 8 No change
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
Sorted List
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
} 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
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
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
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];
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.
Leave the last element i.e., 9 and restore heap from the list “myList[0] ... myList[2]”.
Now, leave the last element i.e., myList[2] and restore the heap from the list “myList[0] ... myList[1]”
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]
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
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
Swap 4 8 9 7
8 9
Swap 22
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
Short Questions
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]
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]
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]
8, 20, 9, 4, 15, 10, 7, 22, 3, 12. (Refer Q45) Nov./Dec.-18, Q12(b) [OU]
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
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.
9. External sorting consists of two phases the _____ and the merge phase.
KEY
I. Multiple Choice
1. (d) 2. (a) 3. (d) 4. (a) 5. (a)
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)
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.
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.