0% found this document useful (0 votes)
3 views274 pages

Data Structures

This document introduces data structures, covering their classification, operations, and the significance of pointers, structures, and algorithms. It explains the concept of stacks, their representation using arrays, and various operations such as traversing, insertion, deletion, searching, and sorting. Additionally, it discusses pointers, their usage in dynamic memory allocation, and provides examples of pointer operations in programming.

Uploaded by

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

Data Structures

This document introduces data structures, covering their classification, operations, and the significance of pointers, structures, and algorithms. It explains the concept of stacks, their representation using arrays, and various operations such as traversing, insertion, deletion, searching, and sorting. Additionally, it discusses pointers, their usage in dynamic memory allocation, and provides examples of pointer operations in programming.

Uploaded by

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

UNIT

01

D
E
Introduction to Data Structures

V
R
E
Names of Sub-Units
S
E
Introduction to Data Structure: Classification of Data Structures, Data Structure Operations, Basic
R
Concepts of Pointers, Structures and Union, Algorithm, Characteristics of the Algorithm.
T

Overview
H

This unit begins by discussing about the concept of Stacks. Next, the unit discusses the Operations
of stack, representing stack using static arrays. Further the unit explains the Dynamic array for
IG

representing stack. Towards the end, the unit discusses the application of stack.
R

Learning Objectives
Y

In this unit, you will learn to:


Discuss the concept of data structures
P

a Explain the concept of classification of data structures


O

a Describe the operations of data structure


Explain the significance of basic concepts of pointers, structures and union
C

a Discuss the characteristics of the algorithm


JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of Data Structure
a Assess the concept of classification of data structure
a Evaluate the importance of operations of data structure
a Determine the significance of Algorithm

D
a Explore the characteristics of algorithm

E
Pre-Unit Preparatory Material

V
a [Link]

R
a [Link]

E
1.1 INTrODUcTION

S
A data structure is a defined format for managing, assessing, retrieving and storing data. Data
structures make it easy for users to work with the data they require in different ways. data structure
E
is designed or selected for storing the data to use different algorithms, in Computer programming. The
basic algorithm operations are integrated into the design of the data structure. Each data structure has
R
information related to the data values, the association between data and functions which are applied
to the data.
T

1.2 DaTa STrUcTUreS


H

Data structure is a way to store and organise data in computer memory so that data can be used
effectively later. It can be arranged in various ways, such as the mathematical or logical model for
IG

the specific organisation of data is known as data structure. In general, the choice of the data model is
based on two considerations. First, it should be defined structure to exhibit the relationships of data in
the real world. Secondly, the structure should be simple so that one can able to process the data when
R

required. Data structure is the process of arranging data and its functions.
Y

1.3 NeeD Of DaTa STrUcTUre


P

The needs of data structures contain the following: efficiency, re-usability, and invisibility. Data structure
offers a means of establishing, handling, and storage data efficiently. It also comprises the collection of
O

data as well as the actions that can be applied to that data.


Data structures are significant for the following reasons:
C

zz Data structure helps the programmers in effectively managing the data. It serves a greater role in
improving the performance of software or program.
zz Data structures are used in every program or software system to arrange the data efficiently.
zz Data structures enable data to be stored in a particular manner in the memory.
zz Data structure is a significant factor for different efficient algorithms. It enables to manage a large
amount of data, such as a large collection of databases and indexing services, such as hash table.

2
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Data structure helps in data retrieval and search effectively.


zz Data structures manage the retrieval and storage of data and information which can be stored in
secondary and main memory.

1.4 cLaSSIfIcaTIONS Of DaTa STrUcTUre


In the classification of data structure, Trees also originate in the non-primitive and non-linear group
of data structure, using tree we can signify a hierarchical relationship between the data components.
The CREATE operation (it can be definite) results in storing memory for the program components. Data

D
structure is classified into the primitive and non-primitive data structures are as follows:
zz Primitive data structures: Primitive data structures are the basic data structures that can
be operated on machine and data instructions directly. It can be defined by the programming

E
languages. Primitive data types are integer, floating point number, real and pointer.

V
zz Non primitive data structures: Non primitive data structures are the data structures that can be
derived from primitive data structures. Non primitive data structures are stacks, graphs, trees and

R
linked lists

E
1.5 DaTa STrUcTUre OPeraTIONS

S
Data Structure is well-defined as a mathematical or logical model to store data and perform operation
on the stored data. The operations are the purposes using which the data can be managed. All the data
E
structure has some common operations to manipulate data and process it for the user. The operation
on data structures are as follows:
R
zz Traversing: Each data structure has a set of data elements. Traversing refers to visiting each
element of data structure to manage operations such as searching or sorting.
T

z For example: if we want to compute the average of marks secured by students in five different
subjects. We need to traverse the array of marks and compute the total sum. We will divide that sum
H

by several subjects, i.e, 5, to compute the average.


Insertion: It is the process of adding elements to the data structures at any location. n is the size of
IG

zz
the data structure and we can insert n-1 data elements into it.
zz Deletion: The phenomenon of removing the element from the data structure is known as deletion.
We delete the element from the data structure at any location. Underflow condition occurs when
R

trying to delete an element from the empty data structure.


Searching: It refers to detecting the location of the element in the data structure is known as
Y

zz
searching. Linear search and binary search are the two algorithms to evaluate searching.
P

zz Sorting: It refers to the phenomenon of organising the data structure in a particular order is called
sorting. Several algorithms can be used to evaluate sorting. Example: selection sort, insertion sort
O

and bubble sort.


Merging: The two lists such as List X and List Y of size of K and L, respectively. They have the identical
C

zz
type of elements combined to generate the third list, List Z of size (K+L). This phenomenon is known
as merging.

1.6 POINTerS
A Pointer is a derived data type that stores the address of another variable. A Pointer contains memory
addresses as their values. Pointers can be used to assign, access, and manipulate data values stored in
the memory allotted to a variable since it can access the memory address of that variable.

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Further description about the Pointer is discussed below:

1.6.1 Pointer Basics


Pointers are the variables that can be used to store the location of value found in the memory. It refers to
the location that holds its memory address. The phenomenon of acquiring value stored at the location
is a reference by the pointer is called dereferencing. It is the same as an index for textbooks where each
page can be referred by the page number found in index. By using this concept, one can able to identify
the page using the location referred to a particular index. These pointers are used in the dynamic
implementation of different data structures, such as lists or stacks. An example of pointer basics that
is declaring pointers is given below:

D
zz Declaring pointers: Pointer declarations is * operation. The syntax is,

E
int a=12;
int *ptr; //pointer declaration

V
pte =&a; // pointer initialization
from the given example, p is a pointer and its type is termed as a pointer to int, it stores the address

R
of integer variable.

E
1.6.2 Pointer with functions

S
You can use the function pointers to eliminate code redundancy. Example: qsort() is used to sort arrays in
descending or ascending order concerning an array of structures. By using void pointers and function
E
pointers, it is significant to use qsort for any type of data type. Function pointers are the pointers
(variable) that refer to the address of the function. It will call functions at run time. The functions are
R
evaluated at run time is known as late binding.
Syntax:
T

Returntype (*function pointer) (parameter1, parameter2);


Function pointer refers to point to function with a particular sign. All these functions have the same
H

parameters and return type. Function pointer and function whose address is referred to have the same
sign. Sign represents that number of parameters, return type and parameters data type of function is
IG

the same. For example:


int (*pfunc) (int l, int M);
// pfunc generally takes integers as return values and parameters.
R

int plus (int l, int K)


//in this function, the address is valued by the function pointer.
Y

1.6.3 Pass by reference


P

Programming languages, such as C, C++ and Java use pass by value. It can be simulated passing by
reference with help of dereferenced pointers as arguments in function definition and passing in the
O

address of the operator and on variables while calling the function. It can be passed in as a copy of the
pointer but it points to the same address in memory as the original pointer. It enables the function to
C

change value outside the function. The arguments passed inside the function are termed as dereferenced
pointers. According to the programmer’s perspective, it is the same as working with the values. By using
the same structure in the swap function using pointers, the values outside the function will be swapped.
Sample program:
If we run the above example, the values will be sapped when swap() function has been called.
Void swap (int *firstvar, int *secondvar)
{

4
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

int temp;
// dereferenced pointers refers to the function is working with values at
addresses which can be passed in
temp=*firstvar;
*firstvar=*secondvar;
*secondvar=temp;
return;
}
int main(void)
{

D
int m = 100;
int n = 200;

E
printf("before swap: value of m: %d \n", m);
printf("before swap: value of n: %d \n", n);

V
// using "address of" operator to pass in the address of each variable
swap(&m, &n);

R
//check values outside the function after swap function.
printf("after swap: value of m: %d \n", m);

E
printf("after swap: value of n: %d \n", n);
return 0;
}
S
E
1.6.4 array of Pointers
R
Array of pointers is an indexed set of variables where the variables are called pointers. Pointers are
significant tool for developing, utilising and eliminating all forms of data structures. Array of pointers
is helpful for reasons which allow to index large sets of variables numerically. Each pointer in one array
T

points to the integer in another array. It can be printed by dereferencing the pointers. This code displays
H

the value in memory of where pointers refer.


An sample program for array of pointers is as follows:
IG

#include <iostream>
using namespace std;
const int MAX = 4;
R

int main () {
int var[MAX] = {20, 200, 400 ,600};
Y

for (int i = 0; i < MAX; i++) {


cout << "Value of var[" << i << "] = ";
P

cout << var[i] << endl;


O

}
return 0;
}
C

The running output of an pointer of array is as follows:


Value of var[0] = 20
Value of var[1] = 200
Value of var[2] = 400
Value of var[3] = 600

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

1.6.5 Pointer to array

Pointer to an array is also acknowledged as array pointer. We are using the pointer to access the
constituents of the array. We have a pointer that emphasis to the (0th) component of the array. We can
similarly declare a pointer that can point to entire array rather than just a single component of the
array. Declaration of the pointer to an array. Declaration of pointer to an array:
extern char (*p)[];
char arr[10];
char (*p)[10] = &arr;

D
The given declaration refers to the pointer to an array of four integers. In this case, we use parenthesis
to denote pointer to an array. It is important to encounter pointer name and indirection operator inside

E
brackets. Sample program for pointer to array is given below:
#include <iostream>

V
using namespace std;
int main () {

R
// an array with 5 elements.
double balance[5] = {1000.0, 5.0,2.4, 27.0, 56.0};

E
double *p;
p = balance;
cout << "Array values using pointer " << endl;
S
E
for ( int i = 0; i < 5; i++ ) {
cout << "*(p + " << i << ") : ";
R
cout << *(p + i) << endl;
}
cout << "Array values using balance as address " << endl;
T

for ( int i = 0; i < 5; i++ ) {


cout << "*(balance + " << i << ") : ";
H

cout << *(balance + i) << endl;


}
IG

return 0;
}
R

The running output of a pointer to array with 5 elements is as follows:


Y

Array values using pointer


*(p + 0): 1000
P

*(p + 1): 5
*(p + 2): 2.4
O

*(p + 3): 27
*(p + 4): 56
C

Array values using balance as address


*(balance + 0): 1000
*(balance + 1): 5
*(balance + 2): 2.4
*(balance + 3): 27
*(balance + 4): 56

6
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

From this program, we can see pointer, which denotes 0th element of the array. We declare a pointer that
can point to an array instead of one element of an array. This pointer is used in the multidimensional
arrays. Syntax for a pointer to array of integer 5
data_type (*var_name)[size_of_array];
Example:
int (*ptr)[5];
From the given example, ptr is the pointer which refers to an array of 5 integers. The given subscript has
high precedence than indirection and it is essential to use the pointer name and indirection operation
inside parentheses. Data type of ptr is a pointer to an array of 5 integers.

D
1.7 DyNaMIc MeMOry aLLOcaTION fUNcTIONS

E
In programming, we can see some situations where we may have to manage data that is dynamic. At

V
the time of program execution, the number of data items may change. Several programming languages
prefer dynamic memory allocation to assign memory for runtime variables. The allocation heap will be

R
used which selects pointers. Pointers hold the address of a dynamically created array of data blocks or
objects. Many structure languages choose free stores to provide storage locations. The dynamic memory

E
allocation function is as follows:
zz Malloc() zz Realloc()
zz Calloc() zz
S
Free()
E
1.7.1 The malloc() function
R
The malloc() function allocates a single block of requested memory. It returns null when the memory is
insufficient. It does not initialise the memory during execution time as it has garbage value. Syntax for
T

malloc() is :{ptr=(cast-type*)malloc(byte-size)}.
H

Let us see the example of malloc() function is given below:


#include <iostream>
IG

#include <cstdlib>
using namespace std;
int main()
R

{
int *my_pointer;
my_pointer = (int*) malloc(5*sizeof(int));
Y

if(my_pointer)
P

{
cout << "Lets intilize 5 memory blocks with odd numbers" << endl << endl;
O

for (int i=0; i<5; i++)


{
C

my_pointer[i] = (i*2)+1;
}
cout << "Lets see the values" << endl << endl;
for (int i=0; i<5; i++)
{
cout << "Value at position "<<i << " is "<< *(my_pointer+i) << endl;
}
free(my_pointer);
return 0;

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

}
}
The running of a Malloc() function is given below:
Lets intilize 5 memory blocks with odd numbers
Lets see the values
Value at position 0 is 1
Value at position 1 is 3
Value at position 2 is 5

D
Value at position 3 is 7
Value at position 4 is 9

E
1.7.2 calloc() function

V
The calloc() Function allocates multi block of requested memory. It initialise all bytes to zero and also
returns null ifmemory is insufficient. Syntax:{ptr=(cast-type*)malloc(byte-size)}.

R
Let us see the example of calloc() function is given below:

E
#include <cstdlib>
#include <iostream>
using namespace std;
int main() { S
E
int *pointer;
pointer= (int *)calloc(6, sizeof(int));
R
if (!pointer) {
cout << "Memory Allocation Failed";
exit(1);
T

}
H

cout << "Initializing values..." << endl


<< endl;
IG

for (int i = 0; i < 6; i++) {


pointer[i] = i * 2 + 1;
}
cout << "Initialized values" << endl;
R

for (int i = 0; i < 6; i++) {


/* ptr[i] and *(ptr+i) can be used interchangeably */
Y

cout << *(pointer + i) << endl;


}
P

free(pointer);
return 0;
O

}
The running output of a Calloc() is given below:
C

Initialized values
1
3
5
7
9
11

8
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

1.7.3 realloc() function


When the memory is insufficient for calloc() or malloc(), we can reallocate the memory using realloc(). It
rearranges or changes the memory size.
Let's us see an example of realloc() function is as follows:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()

D
{
int *ptr, *new_ptr;

E
ptr = (int*) malloc(6*sizeof(int));
if(ptr==NULL)

V
{
cout << "Memory Allocation Failed";

R
exit(1);
}

E
for (int i=0; i<6; i++)
{

}
ptr[i] = i;
S
E
new_ptr = (int*) realloc(ptr, 0);
if(new_ptr==NULL)
R
{
cout << "Null Pointer";
T

}
else
H

{
cout << "Not a Null Pointer";
IG

}
return 0;
}
R

The output of a realloc() function is given below:


Null Pointer
Y

1.7.4 free() function


P

The free() is allocated by calloc() or malloc() should be released by using free(0 function. It needs to be
O

mentioned or else it consumes memory until the program exit. Syntax for free() function is :
{free(ptr)}.
C

Let's see an example of free() function is given below:


#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int x = 8;

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

int *pointer1 = NULL;


int *ptr2 = &x;
if(pointer1)
{
cout << "Pointer is not Null" << endl;
}
else
{
cout << "Pointer is Null" << endl;
}

D
free(pointer1);
cout << *ptr2;

E
return 0;
}

V
The running output of a free() function is given below:

R
Pointer is Null
8

E
1.8 STrUcTUreS

S
Structure is a user defined data type that allows storing the amount of different data types. In structure, each
E
element is called a member. It can assess the use of templates and classes as it stores different information.
The keywords struct is used to define the structure.
R

Syntax for structures is given as:


struct structurename
T

{
H

Datatype member1;
Datatype member2;
IG

...
Datatype member;
};
R

Example of a structure is as follows:


struct employee
Y

{ int id;
char name[10];
P

float salary;
};
O

1.8.1 Self-referential Structures


C

Self-referential structure refers to the structure have members which refer to structure variable of the
same type. It can be used in dynamic data structures, such as linked list and trees. The definition of self-
referential structure is mentioned here,
struct node {
int d;
struct node *k;
};

10
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

In the given structure, k is a pointer to struct node variable. It is similar to the pointer to structure
and pointer to any other variable. It is a structure definition that has one member that is a pointer to
a structure of its kind. These structures are essential in applications of linked data structures such as
trees and lists. Contrary, the static data structure such as array where several elements that can be
inserted in the array is restricted by size of the array. It can be expanded or contracted. Operations such
as deletion or insertion of nodes in self-referential structures are straight forward alteration of pointers.

1.9 UNIONS

D
Union can be defined as user defined data type which has a collection of different variables of different
data types in a same memory location. It can be defined as several members but one member has a

E
value at a specific point in time. It is a user defined data type but structures share the same memory
location.

V
For example :

R
Union
{

E
Char y;
int x;
} u;
S
E
The given example is user defined structure that has two members such as ‘x’ of type int and ‘y’ of type
character. If we evaluate the addresses of ‘x’ and ‘y’, we can see that the addresses are distinct. We can
R
conclude that members in structure do not share the same memory location. Like structure, we define
the union in the same way but union keyword is used for defining union data type. Union contains the
data members, i.e., ‘x’ and ‘y’, also evaluate the addresses of both variables and identified that both
T

variables have the same addresses. It states that union members share the same memory location.
H

1.10 aLgOrIThM
IG

Algorithm is defined as a finite sequence of instructions that can be performed in a finite amount of
effort in a given length of time. Algorithm should be simple and easy to understand. To execute by the
computer, we need a program that needs to be written in a formal language. Computers are not flexible
R

compared to the human mind so programs must contain more information than algorithms. Here, we
may ignore the programming details and focus on the design of algorithms than programs.
Y
P

1.10.1 characteristics of algorithm


O

Every algorithm has some important characteristics which need to be followed. The characteristics of
algorithm are described in detail given below:
C

zz Input specified: During the computation, the input is data to be transformed to generate the output.
Algorithm must have well defined or 0 inputs. Input precision needs to know what kind of data, what
type of data and how much should be.
zz Output specified: The output is the data obtained from the computation. Algorithm must have well
defined or 1 output. Output precision needs what kind of data, what form the output and how much
the output be.

11
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz effectiveness: If the algorithm wants to be effective, it is significant to get output to be feasible with
the available resources. It does not have redundant and unnecessary steps which could make an
algorithm ineffective.
zz finiteness: The algorithm should stop eventually. Stopping refers to that you get expected output
that has no possible solution. Algorithm should terminate after a finite number of steps is made.
Algorithm should always terminate after a defined number of steps and not be infinite. It is
significant to create a finite algorithm.
zz Definiteness: Algorithm should specify every step and the steps must be involved in the process.
Definiteness means mentioning the sequence of operations for making input into output. Algorithm

D
should be unambiguous. Each step should be spelled out and must have quantitative data.

E
1.10.2 elements of algorithm

V
Algorithms are a sequence of instructions, implemented using programming languages, such as java,
C, C++ and so on. The elements of the algorithm are as follows:

R
zz Selection: It is the use of conditional statements such as if then and if then else

E
zz Sequence: It is the order in which commands and behaviours are integrated into projects to generate
expected outcomes.
zz
S
Iteration: Algorithms prefer repetition to execute the steps to a particular number of times or when
a particular condition is attained. It is called looping. It changes the project flow by repeating the
E
behavior until a condition is met.
R

Conclusion 1.11 cONcLUSION


T

zz A data structure is a defined format for managing, assessing, retrieving and storing data. Data
Structures make it easy for users to work with the data they require in different ways.
H

zz The needs of data structures contain the following: efficiency, re-usability, and invisibility.
IG

zz In the classification of data structure, Trees also originate in the non-primitive and non-linear group
of data structure.
zz Data Structure is well-defined as a mathematical or logical model to store data and perform
R

operation on the stored data.


A Pointer is a derived data type that stores the address of another variable.
Y

zz
P

1.12 gLOSSary
O

zz algorithm: a technique used to solve the problem


allocation: allocating memory for an object in the memory
C

zz

zz Data: contains information


zz Pointer: variable who value is the address of another variable
zz Dynamic memory allocation: programming technique where linked objects in data structures are
developed from free store. If no longer is needed, then the object is left as garbage or returned to a free
store.

12
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

1.13 SeLf-aSSeSSMeNT QUeSTIONS

a. Multiple choice Questions


1. What are the functions of data structure?
a. Data retrieval
b. Searching

D
c. Arrangement of data
d. All of these

E
2. __________ are the basic data structures that can be operated on machine and data instructions

V
directly.
a. Primitive data structures

R
b. Non-primitive data structures

E
c. Linear data structures
d. None of these
S
3. Which of the following data structure is a nonlinear type?
E
a. Lists
R
b. Strings
c. Stacks
T

d. None of these
H

4. Which of the following data structures are in linear type?


a. Lists
IG

b. Queues
c. Strings
R

d. All of these
5. Which is true from the following for prior using a pointer variable?
Y

a. It should be declared
P

b. It should be initialised
O

c. It should be both declared or initialised


d. None of these
C

6. Comment on following declaration Int *ptr l;


a. Ptr and l are pointers to integer
b. Ptr is a pointer to integer, l is not
c. Ptr and p are not pointers to integers
d. Ptr is a pointer to integer, l may or may not be

13
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

7. When the user attempts to remove the element from the empty stack then the condition is said to be
a _______
a. Underflow
b. collection of garbage
c. overflow
d. None of these
8. Which data structure is generally used for executing the recursive algorithm?

D
a. Queue
b. Stack

E
c. Heap sort

V
d. Linked list

R
9. Which among the following is the method of inserting an element in the stack?
a. Insert

E
b. Add
c. Push
S
E
d. None of these
10. What is alternative name for the circular queue from the following options?
R
a. Cone buffer
b. Square buffer
T

c. Ring buffer
H

d. None of these
IG

B. essay Type Questions


1. The basic algorithm operations are integrated into the design of the data structure. Each data
R

structure has information related to the data values. What is a Data structure?
2. Data structure offers a means of establishing, handling, and storage data efficiently. It also comprises
Y

the collection of data as well. Explain the need of data structures.


P

3. Trees also originate in the non-primitive and non-linear group of data structure, using tree we can
signify a hierarchical relationship between the data components. Describe the classification of data
O

structure.
4. In programming, we can see some situations where we may have to manage data that is dynamic.
C

At the time of program execution, the number of data items may change. Describe the significance
of dynamic memory allocation functions.
5. To execute by the computer, we need a program that needs to be written in a formal language.
Determine the importance of algorithm.

14
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

1.14 aNSwerS aND hINTS fOr SeLf-aSSeSSMeNT QUeSTIONS

a. answers to Multiple choice Questions

Q. No. answer
1. d. All of these

D
2. a. Primitive data structures

3. d. None of these

E
4. d. All of these

V
5. c. It should be both declared or initialised

R
6. a. Ptr and l are pointers to integer

7. a. Underflow

E
8. b. Stack

9. c. Push
S
E
10. c. Ring buffer
R
B. hints for essay Type Questions
1. Data structure is a way to store and organise data in computer memory so that data can be used
T

effectively later. It can be arranged in various ways, such as the mathematical or logical model for
the specific organisation of data is known as data structure. Refer to Section Data structures
H

2. The needs of data structures contain the following: efficiency, re-usability, and invisibility. Data
IG

structure offers a means of establishing, handling, and storage data efficiently. It also comprises
the collection of data as well as the actions that can be applied to that data. Refer to Section Need of
Data structures
R

3. In the classification of data structure, Trees also originate in the non-primitive and non-linear
group of data structure, using tree we can signify a hierarchical relationship between the data
Y

components. Refer to Section Classification of Data Structure


4. Dynamic memory allocation is used assign memory for runtime variables. The allocation heap will
P

be used which selects pointers. Pointers hold the address of a dynamically created array of data
O

blocks or objects. Many structure languages choose free stores to provide storage locations. Refer to
Section Dynamic Memory Allocation Functions
C

5. Algorithm is defined as a finite sequence of instructions that can be performed in a finite amount
of effort in a given length of time. Algorithm should be simple and easy to understand. To execute
by the computer, we need a program that needs to be written in a formal language. Refer to Section
Algorithm

15
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

@ 1.15 POST-UNIT reaDINg MaTerIaL

zz [Link]
zz [Link]

1.16 TOPIcS fOr DIScUSSION fOrUMS

D
zz You can discuss with your friends the applications of data structures in a real-life environment,
Classification of data structure and its need . Also discussed on pointers and Algorithm of data
structure.

E
V
R
E
S
E
R
T
H
IG
R
Y
P
O
C

16
UNIT

02

D
E
Arrays

V
R
E
Names of Sub-Units S
E
Introduction to Arrays, Array Representation, Array Operations, Polynomials, Sparse Matrices.
R

Overview
T

This unit begins by explaining the meaning of arrays. Further, it discusses the basic terminology of
H

array representation. Further the unit explains the array operations and polynomials. Towards the
end, the unit discusses the sparse matrices.
IG

Learning Objectives
R

In this unit, you will learn to:


Y

a Discuss the concept of arrays


Explain the concept of array representation
P

a Describe the array operations


O

a Explain the significance of polynomials and sparse matrices


C

Learning Outcomes

At the end of this unit you would:


a Evaluate the concept of arrays
a Assess the concept of array representation
a Evaluate the importance of array operations
a Determine the significance of polynomials and sparse matrices
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Pre-Unit Preparatory Material

a [Link]
a [Link]

2.1 INTRODUCTION
Array is a vessel which carries a fixed quantity of data items which should be of identical kind or same
datatype. Most of the algorithms implemented by different Data structures use arrays. Arrays are

D
described by two basic terms, which acts as integral part of an array is given below:
Element: The constituent data items collectively stored in an array are known as its elements.

E
zz

zz Index: The position of an element is assigned a numerical index, which recognises the element is

V
referred as its index.

R
2.2 REPRESENTATION OF LINEAR ARRAYS IN MEMORY
There are various ways to declare the array in different programming languages. Lets consider the

E
array declaration as shown in Figure 1:

S
E
Elements 35 33 42 10 14 19 27 44 26 31
R
index 0 1 2 3 4 5 6 7 8 9

Size: 10
T
H

Figure 1: Array Declaration


From the above depiction, following points are worth considering:
IG

zz 0 marks as the starting position of the array. It is considered as the first element.
zz The size of the array is 10 which denote that it stores 10 elements.
R

zz Any element can be retrieved through its index. For instance, we can access the element 19 from its
index 5.
Y

2.3 FUNCTIONS OF ARRAYS


P

An array function is generally well-defined as a function that works with an array. The array is a mutual
O

perception in computer programming, where several variables are assigned together with a common
name. Variables are specific items that enclose numbers, letters or other data.
C

2.3.1 Traverse Operation


Displays all the array elements individually. This operation allows us to visit all the elements of an array
by traversing through it. The following program implements the Traverse operation:
#include <stdio.h>
void main()
{

2
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY

int LA[] = {1,3,7,9,11,13};


int i, n = 6;
printf("The array elements are:\n");
for(i = 0; i < n; i++)
{
printf("LA[%d] = %d \n", i, LA[i]);
}
}
The running output of a Traverse operation is as follows:

D
The array elements are:
LA[0] = 1

E
LA [1] = 3
LA [2] = 7

V
LA [3] = 9
LA [4] = 11

R
LA [5] = 13

E
2.3.2 Insertion Operation

S
This operation allows us to insert either single or multiple data items into an array. Depending on the
situation, a new element can be added at any position as specified by index of element in the array.
E
The following program illustrates the Insert operation, where a data item is inserted at the specified
R
location in the array. The following program implements the Insertion operation:
#include <stdio.h>
void main()
T

{
int LA[] = {3,5,7,9,11};
H

int item = 11, K = 3, N= 5;


int i = 0, j = N;
IG

for(i = 0; i<N; i++)


{
printf("LA[%d] = %d \n", i, LA[i]);
R

}
N = N + 1;
Y

while( j >= K)
{
P

LA[j+1] = LA[j];
j = j - 1;
O

}
LA[K] = item;
C

printf("The array elements after insertion:\n");


for(i = 0; i<N; i++)
{
printf("LA[%d] = %d \n", i, LA[i]);
}
}

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The running output of Insertion operation is given below:


LA [0] = 3
LA [1] = 5
LA [2] = 7
LA [3] = 9
LA [4] = 11
The array elements after insertion:
LA [0] = 3
LA [1] = 5

D
LA [2] = 7
LA [3] = 11
LA [4] = 9

E
LA [5] = 11

V
2.3.3 Deletion Operation

R
The process of removing an existing element, from an array, then reassembling all the elements of the
array is termed as Deletion. Removes an element at the specified index from an array. Consider a linear

E
array Sample, with Max number of elements and Loc, is a positive integer where Loc<=Max. Following
algorithm depicts the process of deletion of an element present at the Locth position of sample:
zz Begin S
E
zz Set TmpVar = Loc
R
zz Repeat steps 4 and 5 while TmpVar < Max
zz Set Sample[TmpVar] = Sample[TmpVar+ 1]
Set TmpVar = TmpVar+1
T

zz

Set Max = Max-1


H

zz

zz Finish
IG

The following program implements the Deletion operation:


#include <stdio.h>
void main()
R

{
int LA[] = {3,5,7,9,12};
Y

int K = 3, N = 5;
int i, j;
P

printf("The original array elements are:n");


O

for(i = 0; i<N; i++)


{
printf("LA[%d] = %d n", i, LA[i]);
C

}
j = K;
while( j < N)
{
LA[j-1] = LA[j];
j = j + 1;

4
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY

}
N = N -1;
printf("The array elements after deletion:n");
for(i = 0; i<N; i++)
{
printf("LA[%d] = %d n", i, LA[i]);
}
}
The running output of a Deletion operation is given below:

D
The original array elements are: nLA[0] = 3 nLA[1] = 5 nLA[2] = 7 nLA[3]
= 9 nLA[4] = 12 nThe array elements after deletion: nLA[0] = 3 nLA[1] = 5

E
nLA[2] = 9 nLA[3] = 12 n

V
2.3.4 Search Operation
Search Operation could be performed on an array based on either the value or index of the element. :

R
Looks for an element provided with respective index. Consider a linear array Sample with Max number
of elements and is a positive integer where Loc<=Max. Following algorithm helps to locate an element

E
using its value through sequential search is as follows:
zz Begin
Set TmpVar = 0
S
E
zz

zz Repeat steps 4 and 5 while TmpVar < Max


R

zz IF Sample[TmpVar] is equal to Elmnt THEN proceed to STEP 6


zz Set TmpVar = TmpVar+1
T

zz PRINT TmpVar, ITEM


H

The following program implements the Search operation:


#include<stdio.h>
IG

int main()
{
int arr[10], Size, i, Search, Flag;
R

printf(" 2, 4 ,6, 7, 9 , 11 , 13 , 15 , 17\n ");


scanf("%d",&Size);
Y

printf("\n Please Enter %d elements of an array: \n", Size);


for(i = 0; i < Size; i++)
P

{
O

scanf("%d",&arr[i]);
}
printf("\n Please Enter the Search Element :9 ");
C

scanf("%d",&Search);
Flag = 0;
for(i = 0; i < Size; i++)
{
if(arr[i] == Search)
{

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Flag = 1;
break;
}
}
if(Flag == 1)
return 0;
}
The running output of Search operation is given below:
2, 4, 6, 7, 9, 11, 13, 15, 17

D
2.3.5 Update Operation

E
The process of modifying an existing element in an array at a specified index is referred to as updating.
It modifies an element in the specified index position. Consider a LinearArray Sample, with Max number

V
of elements and Loc,is a positive integer where Loc<=Max. Following algorithm shows the process of
updating an element present at the Loc th position of Array Sample is as follows:

R
zz Begin

E
zz Set Sample[Loc-1] = Elmnt
zz Finish

The following program implements the Update operation:


S
E
#include <stdio.h>
R
void main()
{
int LA[] = {2,9,7,11,16};
T

int K = 3, N = 5, item = 11;


int i, j;
H

printf("The original array elements are:\n");


for(i = 0; i<N; i++)
IG

{
printf("LA[%d] = %d \n", i, LA[i]);
}
R

LA[K-1] = item;
printf("The array elements after updation:\n");
Y

for(i = 0; i<N; i++)


{
P

printf("LA[%d] = %d \n", i, LA[i]);


}
O

}
The running output of Update operation is given below:
C

The original array elements are:


LA [0] = 2
LA [1] = 9
LA [2] = 7
LA [3] = 11
LA [4] = 16
The array elements after updation:

6
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY

LA [0] = 2
LA [1] = 9
LA [2] = 11
LA [3] = 11
LA [4] = 16

2.4 MULTIDIMENSIONAL ARRAYS


A multidimensional array connects each component in the array with numerous indexes. Generally,
multidimensional array is the two-dimensional array, also recognized as a table or matrix. A two-

D
dimensional array links each of its components with two indexes.
Multidimensional arrays are well-defined analogously. More precisely, an n dimension m1 x m2

E
... x mn array B is a group of m1, m2 , ..., mn data components in which each component identified
by a list of n integers such as K1, K2....., Kn called subscripts with the property that (1<=K1<=m.

V
1<=k2<=m2...........1<=Kn<=mn).

R
2.4.1 Size of Multidimensional Arrays

E
The Total elements of a multidimensional array can be obtained from the product of the dimensional
sizes of the array For example The array int [] [] x = new int [10] [20] can store a total of (10*20) = 200
elements. S
E
2.4.2 Two-Dimensional Array
R

The Two Dimensional Array is nothing but an Array of Arrays. If the data is linear, we can use the One
Dimensional Array. Though, to work with multi-level data, we must to use the Multi-Dimensional Array.
T

It is the modest form of Multi-Dimensional Array. Two Dimensional Array, data is kept in row and column
wise. We can access the record using both the row index and column index. The basic declaration of two
H

dimensional arrays is as shown below:


{Data type Array Name [Row Size][Column Size]}
IG

A two dimensional array is the most elementary form of a multidimensional array. We view a two
dimensional array as a table of one dimensional array for comprehending in a better way.
R

A two-dimensional array could be declared in the following way:


zz Data_type Name_Of_Array[x][y];
Y

zz Data_type: refers to kind of data for storage which could be any valid C or C++data type
P

We can initialize the Two Dimensional Array in several ways. A Two-Dimensional array can be initialised
by four different approaches is as follows:
O

zz First approach for two dimensional arrays: The first three components will be 1st row, the second
three components will be 2nd row, the next 3 components will be 3rd row, and the last 3 components
C

will be 4th row. Here we separated them into 3 because our column size is 3. For example : int
Employees[4][3] = { 10, 20, 30, 15, 25, 35, 22, 44, 66, 33, 55, 77 };
zz Second approach for two dimensional arrays: Here, we haven’t stated the row size and column size.
Though, the compiler is intelligent and sufficient to calculate the size by read-through the number
of components inside the row and column. For example: int Employees [ ][ ] = { {1 4, 22, 36}, {17, 28, 37},
{20, 47, 65}, {41, 50, 59} };

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz Third approach of two dimensional arrays: Here, we acknowledged Employees array with row size
=2 and column size = 3, but we only allocated 1 column in the 1st row and 2 columns in the 2nd row.
In these circumstances, the residual values will assign to avoidance values (0 in this case).
For example:
int Employees [1][2] = { {3},
{8, 9 }
};
zz Fourth approach for two dimensional arrays: The above three methods of initializing two

D
dimensional array are decent to accumulate a small number of components into the array. What
if we want to accumulate 100 rows or 50 column values? It will be a frightening to add all of them
using any of the approaches stated above. To resolve this, we can use the for loop:

E
int rows, columns, Employees[100][50];

V
for (rows =0; rows < 100 ; rows++)
{

R
for (columns =0; columns < 50; columns++)
{

E
Employees [rows][columns] = rows + columns;
}
S
The following algorithm is for two-dimensional array is as follows:
E
#include <stdio.h>
#include <stdlib.h>
R
int main()
{
int X[3][4]={{2,3,4,5},{5,6,7,8},{2,4,8,9}};
T

int i,j;
for(i=0;i<3;i++)
H

{
for(j=0;j<4;j++)
IG

{
printf("%d ",X[i][j]);
}
R

printf("\n");
}
Y

return 0;
}
P

The running output of a Two dimensional array is given below:


O

2 3 4 5
5 6 7 8
C

2 4 8 9

2.4.3 Three Dimensional Array


A three-dimensional array can be assumed as an array of arrays of arrays. The outer array has three
components, each of which is a two-dimensional array of four one-dimensional arrays, each of which
comprises two integers.

8
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY

Figure 2 is visualizing the situation of 3-D array:

Columns

Column1 Column2 Column3

Row 1 111 112 113 Array 1

Ar

D
ra
Rows

ys
Row 2 121 211 212 213 Array 2

E
221 311 312 313 Array 3
Row 3 131

V
321 322 323

R
231

E
331 332 333

S
E
Figure 2: Visualization of 3-D Array
R
The process of initializing the three-Dimensional arrays is similar to that of Two-dimensional arrays.
The variation lies in the fact that is as there is an increase in the number of dimensions, there is an
increase in the number of nested braces.
T

Retrieving elements from three-dimensional arrays: Fetching the elements of three-dimensional arrays
H

follows a similar approach as that of the two-dimensional arrays.


IG

The variation is that three loops are required rather than two loops to work with the additional dimension
present in three dimensional arrays.
The following algorithm is for Three-dimensional array is as follows:
R

#include<iostream>
using namespace std;
Y

int main()
{
P

int i, j, k;
O

int threeDimArr[3][4][2] = {
{ {2, 3}, {5, 6}, {4, 2}, {5, 9} },
{ {7, 9}, {8, 9}, {6, 5}, {4, 3} },
C

{ {1, 2}, {4, 6}, {8, 3}, {5, 7} }


};
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{

9
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

for(k=0; k<2; k++)


cout<<threeDimArr[i][j][k]<<" ";
cout<<endl;
}
cout<<endl;
}
cout<<endl;
return 0;
}

D
The running output of a Three dimensional array is given below:
2 3

E
5 6
4 2

V
5 9

R
7 9
8 9

E
6 5
4 3

1 2
S
E
4 6
8 3
R

5 7
Similarly, arrays with multiple dimensions could be created following a similar approach. But we
T

must be cautious as the increase in the dimensions makes the arrays more complex to deal with.
The widely used multidimensional array is the two-dimensional array.
H

2.5 POLYNOMIAL
IG

A polynomial q(x) is a function with variable x taking the form (axn + bxn-1 + …. + jx+ k), where a, b, c
…., till k are real numbers and ‘n’ is a positive integer, which is known as the degree of the polynomial.
R

An important feature of the polynomial is that its individual term contains two components are:
zz Coefficient
Y

zz Exponent or Power
P

For example: 5x2 + 6x, 5 and 6 are referred as the coefficients of variable and 2, 1 are the exponents.
O

Points to consider while using the polynomials is as follows:


The sign of the individual coefficients and exponents are reserved inside the coefficient and the
C

zz
power (exponent) itself.
zz The possibility of the presence of additional terms with equal exponent is one.
zz The memory assignment for the individual terms of the polynomial is done either in ascending or
descending order of their exponents.

10
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY

The insertion of coefficient and power is shown in Figure 3:

poly
Coefficient

4x3 + 6x2 + 10x + 6

4 3 6 2 10 1 6 0

D
E
Power

V
Figure 3: Insertion of Coefficient and Power

R
2.5.1 Polynomial Representation

E
A polynomial is an appearance that comprises more than two terms. A term is made up of coefficient
and exponent. An example of polynomial is a polynomial so, it may be represented by means of arrays
or linked lists. S
E
The concept of polynomials can be implemented through the following data structures:
Arrays
R
zz

zz Linked List
T

2.5.2 Representing Polynomials Using Arrays


H

In the situations which involve evaluating multiple polynomial expressions and performing the arithmetic
operations like addition and multiplication on them, we need a path to represent those polynomials. The
IG

simplest way is to represent a polynomial with degree ‘n’ and reserve all the coefficients of n+1 terms of
the polynomial is by storing them in an Array. So each element of the array will now have two values:
zz Coefficient
R

zz Exponent
Y

The following algorithm represents the multiplication of polynomials is as follows:


P

#include <bits/stdc++.h>
using namespace std;
O

int *multiplyTwoPolynomials(int X[], int Y[], int m, int n) {


int *productPolynomial = new int[m+n - 1];
for (int i = 0; i < m + n - 1; i++) {
C

productPolynomial[i] = 0;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
productPolynomial[i + j] += X[i] * Y[j];
}

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

}
return productPolynomial;
}
void printPolynomial(int polynomial[], int n) {
for (int i = n - 1; i >= 0; i--) {
cout << polynomial[i];
if (i != 0) {
cout << "x^" << i;
cout << " + ";
}

D
}
cout << endl;

E
}
int main() {

V
int X[] = {5, 6, 7, 8};
int Y[] = {8, 7, 6, 5};

R
int m = 4;
int n = 4;

E
cout << "First polynomial: ";
printPolynomial(X, m);
cout << "Second polynomial: "; S
E
printPolynomial(Y, n);
int *productPolynomial = multiplyTwoPolynomials(X, Y, m, n);
R
cout << "Product polynomial: ";
printPolynomial(productPolynomial, m + n - 1);
return 0;
T

}
The running output of the multiplication of polynomials is given below:
H

First polynomial: 8x^3 + 7x^2 + 6x^1 + 5


IG

Second polynomial: 5x^3 + 6x^2 + 7x^1 + 8


Product polynomial: 40x^6 + 83x^5 + 128x^4 + 174x^3 + 128x^2 + 83x^1 + 40

2.5.3 Polynomial Representation Using Linked Lists


R

Polynomials and Sparse Matrix are two important presentations of arrays and linked lists. A polynomial
Y

is collection of different terms where each of them holds a coefficient and an exponent.
P

The following algorithm represents the multiplication of polynomials using linked list is as follows:
#include<bits/stdc++.h>
O

using namespace std;


struct Node{
C

int coefficient;
int pow;
struct Node *next;
};
void create_node(int X, int Y, struct Node **temp){
struct Node *r, *z;
z = *temp;
if(z == NULL){

12
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY

r =(struct Node*)malloc(sizeof(struct Node));


r->coefficient = X;
r->pow = Y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
} else {
r->coefficient = X;
r->pow = Y;

D
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;

E
r->next = NULL;
}

V
}
void polyadd(struct Node *p1, struct Node *p2, struct Node *result){

R
while(p1->next && p2->next){
if(p1->pow > p2->pow){

E
result->pow = p1->pow;
result->coefficient = p1->coefficient;
p1 = p1->next; S
E
}
else if(p1->pow < p2->pow){
R
result->pow = p2->pow;
result->coefficient = p2->coefficient;
p2 = p2->next;
T

} else {
result->pow = p1->pow;
H

result->coefficient = p1->coefficient+p2->coefficient;
p1 = p1->next;
IG

p2 = p2->next;
}
result->next = (struct Node *)malloc(sizeof(struct Node));
R

result = result->next;
result->next = NULL;
Y

}
while(p1->next || p2->next){
P

if(p1->next){
result->pow = p1->pow;
O

result->coefficient = p1->coefficient;
p1 = p1->next;
C

}
if(p2->next){
result->pow = p2->pow;
result->coefficient = p2->coefficient;
p2 = p2->next;
}
result->next = (struct Node *)malloc(sizeof(struct Node));
result = result->next;

13
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

result->next = NULL;
}
}
void printpoly(struct Node *node){
while(node->next != NULL){
printf("%dx^%d", node->coefficient, node->pow);
node = node->next;
if(node->next != NULL)
printf(" + ");
}

D
}
int main(){

E
struct Node *p1 = NULL, *p2 = NULL, *result = NULL;
create_node(14,8,&p1);

V
create_node(22,7,&p1);
create_node(67,9,&p1);

R
create_node(41,4,&p2);
create_node(19,2,&p2);

E
printf("polynomial 1: ");
printpoly(p1);
printf("\npolynomial 2: "); S
E
printpoly(p2);
result = (struct Node *)malloc(sizeof(struct Node));
R
polyadd(p1, p2, result);
printf("\npolynomial after adding p1 and p2 : ");
printpoly(result);
T

return 0;
}
H

The running output of the addition of Polynomials using linked list is given below:
IG

Polynomial 1: 14x^8 + 22x^7 + 67x^9


Polynomial 2: 41x^4 + 19x^2
Polynomial after adding p1 and p2: 14x^8 + 22x^7 + 67x^9 + 41x^4 + 19x^2
R

2.6 SPARSE MATRIX


Y

We define a Matrix as a two-dimensional array with ‘m’ rows and ‘n’ columns forming an m*n matrix.
Sparse matrices are the matrices in which the majority of the elements are zero's. Alternatively, a
P

sparse matrix is defined as the matrix which has a larger number of zero's than nonzero elements. A
fair question arises if a simple matrix could be used for different purposes; then why we should go for
O

the sparse matrix? Following benefits makes a sparse matrix more relevant:
zz Storage: a sparse matrix needs minimal memory storage, than the normal matrices. It considers
C

only the non-zero elements for any calculation.


zz Computing time: Searching a sparse matrix, requires to traversal of the non-zero elements alone,
instead visiting other elements, which save computing time as we use a logically designed data
structure for moving across non-zero elements.

If we use two dimensional arrays for representing a sparse matrix, it leads to the wastage of precious
memory spaces. The zero's of the matrices need not be stored. We store the non-zero elements alone.
Such storage mechanism reduces the traversal time and the memory space.

14
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY

2.6.1 Sparse Matrix Representation


Sparse matrix representations can be done in numerous ways. The two common representations of
sparse matrix are in linked list, each node has four fields. These four fields are well-defined as a dictionary,
where row and column numbers are used as keys and values are matrix entries. This technique keeps
space but consecutive access of items is expensive.
The non-zero elements of the sparse matrix are stored in triplets, [Link],columns,and value. We can
use the different data structures for representing sparse matrices. Two of them are:
zz Arrays

D
zz Linked lists

E
2.6.2 Representation of Sparse Matrix using Arrays

V
Sparse matrix is a matrix which comprises very insufficient non-zero components. When a sparse
matrix is characterized with a 2-dimensional array, we excess a lot of space to describe that matrix. For

R
example, consider a matrix of size 100 X 100 comprising only 10 non-zero components. In this matrix,
only 10 spaces are occupied with non-zero values and remaining spaces of the matrix are occupied with

E
zero. A Sparse matrix can be represented using a two dimensional array, which has three rows, namely:
zz

zz
S
Row: refers to the index of the row where a non-zero element is found.
Column: refers to the index of the column which has a non-zero element.
E
zz Value: refers to the value of the non-zero element found at the index (row, column).
R

An example of Sparse matrix portraying through array representation is shown in Figure 4:


T

0 1 2 3
Sparse matrix 0 0 4 0 5
H

1 0 0 3 6
2 0 0 2 0
3 2 3 0 0
IG

4 0 0 0 0
R

Figure 4: Representation of Sparse Matrix using Array


Observing the image above, we can get a clear idea of the representation of sparse matrix, which is
Y

achieved via triplets, i.e row, column, and value.


P

The above sparse matrix, has 13 zeroes and 7 non-zero elements. The memory space of 5*4=20 elements
is occupied by the sparse matrix. The increase in the size of the sparse matrix leads to memory wastage.
O

We can represent the above sparse matrix in a tabular format as displayed below:
C

Table structure of a Sparse matrix

Row Column Value


0 1 4
0 3 5
1 2 3
1 3 6

15
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Row Column Value


2 2 2
3 0 2
3 1 3

2.6.3 Representation of Sparse Matrix using Linked List


Linked list representation is used to represent a sparse matrix. In linked list representation, each node

D
contains of four fields while, in array representation there are three fields, i.e., row, column, and value.
We can use the data structure linked lists to represent the sparse matrices.

E
Following are the data fields of a node in the linked list:
Row: Refers to the index of the row where there is a non-zero element.

V
zz

zz Column: Refers to the index of column where a non-zero element is found.

R
zz Value: Refers to the value of the non-zero element which present at the index (row, column).
Next node: Holds the address of the next node.

E
zz

An example of Sparse matrix portraying through linked list representation is shown in Figure 5:
S
E
Linked List Reprsentation
R
0 2 1 0 3 2 1 0 3 2 1 1 2 2 5 3 1 6 NU
T

Figure 5: Representation of Sparse Matrix using Linked List


H

The above image displays how a sparse matrix is represented by linked list. The first field of the node
denotes the row index, second field indicates the i column index, third field denotes the value and fourth
field holds the address of the subsequent node.
IG

Conclusion 2.7 CONCLUSION


R

zz Array is a vessel which carries a fixed quantity of data items which should be of identical kind or
same data type.
Y

zz Sparse matrix as a two-dimensional array with ‘m’ rows and ‘n’ columns forming an m*n matrix.
P

zz A multidimensional array connects each component in the array with numerous indexes.
O

zz An array operation is generally well-defined as a operation that works with an array. The array is a
mutual perception in computer programming.
C

zz Polynomials seem in many areas of mathematics and science. For example, they are used to form
polynomial equations, which convert a comprehensive range of problems.

2.8 GLOSSARY

zz Array: Refers to a homogeneous vessel of numerical elements


zz Multidimensional array: Connects each component in the array with numerous indexes.

16
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Two dimensional array: Kept data in row and column wise.


zz Three-dimensional array: It has a three component of arrays.
zz Sparse matrices: The matrices in which the majority of the elements are zeros.

2.9 SELF-ASSESSMENT QUESTIONS

A. Multiple Choice Questions

D
1. Which of these best describes an array?
a. Arrays is not a data structure

E
b. Arrays are immutable once initialised

V
c. Data structure which exhibits hierarchical behaviour
d. Container of object of same types

R
2. How do you initialize an array in C?

E
a. int a[4] = (8,9,10,11);
b. int a(4) = {8,9,10,11};
c. int a[4] = {8,9,10,11};
S
E
d. int arr(4) = (8,9,10,11);
R
3. How do you instantiate array in Java?
a. int r[] = new int(5);
T

b. int r[];
H

c. int r[] = new int[5];


d. int r() = new int(5);
IG

4. Select the right declaring statement of a multidimensional array in Java?


a. int[] d;
R

b. int d[[]];
c. int[][]d;
Y

d. int[[]] d;
P

5. What is the output of the following Java code?


O

public class array


{
public static void main (String args[])
C

{
int []d = {6,7,8,9,10};
[Link] (d [2]);
[Link] (d [4]);
}
}
}

17
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

a. 8 and 10
b. 7 and 10
c. 8 and 9
d. 6 and 9
6. What is the output of the following Java code?
public class array
{
public static void main (String args[])

D
{
int y[] = {11,12,13,14,15};

E
[Link](y[5]);
}

V
}
a. Invalid input exception

R
b. 5

E
c. Array Index Out of Bounds Exception
d. 4
7. S
When does the Array Index Out of Bounds Exception occur?
E
a. Run time
R
b. Compile time
c. No error occurs
d. Not an exception at all
T

8. Which of the following concepts make extensive use of arrays?


H

a. Binary trees
IG

b. Spatial locality
c. Scheduling of processes
d. Caching
R

9. Which of the following concepts make wide use of arrays?


Y

a. Spatial locality
b. scheduling of processes
P

c. Caching
O

d. Binary trees
10. Which among the following are the advantages of array?
C

a. Objects of assorted data types can be stored


b. Elements in an array cannot be sorted
c. Index of first element of an array is 1
d. Easier to store elements of similar data type

18
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY

B. Essay Type Questions


1. It is a vessel which carries a fixed quantity of data items which should be of identical kind or same
datatype. What is an Array?
2. There are various ways to declare the array in different programming languages. Explain the
significance of representation of linear array in memory.
3. An array function is generally well-defined as a function that works with an array. The array is
a mutual perception in computer programming, where several variables are assigned together.
Describe the importance of functions of array.

D
4. A multidimensional array connects each component in the array with numerous indexes. Generally,
multidimensional array is the two-dimensional array, also recognised as a table or matrix. Determine

E
the functions of Multidimensional array.
5. We define a Matrix as a two-dimensional array with ‘m’ rows and ‘n’ columns forming an m*n matrix.

V
Elaborate the Sparse matrix.

R
2.10 ANSWERS AND HINTS FOR SELF-ASSESSMENT QUESTIONS

E
A. Answers to Multiple Choice Questions S
E
Q. No. Answer
R
1. d. container of object of same types
2. c. int a[4] = {8,9,10,11};
T

3. c. int r[] = new int[5];


4. c. int[][]d;
H

5. a. 8 and 10
IG

6. c. ArrayIndexOutOfBoundsException
7. a. run time
8. b. Spatial locality
R

9. a. Spatial locality
Y

10. d. Easier to store elements of similar data type


P

B. Hints for Essay Type Questions


O

1. Array is a vessel which carries a fixed quantity of data items which should be of identical kind
or same datatype. Most of the algorithms implemented by different Data structures use arrays.
C

Arrays are described by two basic terms, which acts as integral part of an array. Refer to Section
Introduction
2. There are various ways to declare the array in different programming languages. Let’s consider the
array declaration in C. Refer to Section Representation of Linear Array in Memory
3. An array function is generally well-defined as a function that works with an array. The array is a
mutual perception in computer programming, where several variables are assigned together with

19
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

a common name. Variables are specific items that enclose numbers, letters or other data. Refer to
Section Function of Arrays
4. A multidimensional array connects each component in the array with numerous indexes. Generally,
multidimensional array is the two-dimensional array, also recognized as a table or matrix. Refer to
Section Multidimensional Arrays
5. We define a Matrix as a two-dimensional array with ‘m’ rows and ‘n’ columns forming an m*n matrix.
Sparse matrices are the matrices in which the majority of the elements are zeroes.
Alternatively, a sparse matrix is defined as the matrix which has a larger number of zeroes than

D
nonzero elements. Refer to Section Sparse Matrix

E
@ 2.11 POST-UNIT READING MATERIAL

V
zz [Link]
[Link]

R
zz

E
2.12 TOPICS FOR DISCUSSION FORUMS

zz
S
Discuss with your friends and classmates about the concept of Array and its representation .Also;
E
discuss some interesting mathematical problems of polynomials and sparse matrices.
R
T
H
IG
R
Y
P
O
C

20
UNIT

03

D
E
Strings

V
R
E
Names of Sub-Units
S
E
Strings Outlook: Operations on Strings, String Utility Functions, Algorithms for Pattern Matching in
R
Strings.
T

Overview
H

This unit begins by discussing about the concept of string. Next, the unit discusses the operations on
strings. Further the unit explains the string utility functions. Towards the end, the unit discusses the
IG

algorithms for pattern matching in strings.


R

Learning Objectives
Y

In this unit, you will learn to:


P

a Discuss the concept of strings


O

a Explain the concept of operations on strings


a Describe the string utility functions
C

a Explain the significance of strings


a Discuss the algorithms for pattern matching in strings
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of Strings
a Assess the concept of operations on Strings
a Evaluate the importance of strings functions
a Determine the significance of string utility functions

D
a Explore the algorithm for pattern matching in strings

E
Pre-Unit Preparatory Material

V
a [Link]

R
a [Link]

E
3.1 INTrOdUcTION

S
Strings could be viewed as an arrangement of characters, which could be a literal constant or a variable.
The variables can cause the characters to be transmuted and the corresponding length be modified,
E
or it can be kept unchanged since its creation. We can consider String as a data type which is often
used as an Array of bytes which stores the string, containing a sequence of characters through certain
R
character encoding. Strings may indicate the simpler single dimensional Arrays or various sequence
data types and structures. Turning on the prorammeming language and specific data type used, a
T

variable representing a String may either be stored in memory through static memory allocation for
a fixed maximum size or go for dynamic allocation, allowing it to hold a varying number of elements.
H

If a string pops up precisely in source code, it is referred to as a String literal or an anonymous string.
IG

3.2 STrINgS
A String is referred as a data type to be used in prorammeming, By data type we mean an integer type
or a floating point type, however, it represents text instead of numbers. It includes a set of characters
R

and may even have spaces and numbers.


Y

3.3 TerMINOLOgy USed


P

Following points describe the terminology used in strings is as follows:


String length: Defining to size of the string
O

zz

zz copying string: Duplicating one String into another


C

zz concatenation: Joining two different or identical strings


zz comparing string: Contrasting two strings
zz Modifying string: Making changes in the string

3.4 STOrINg daTa IN STrINgS


Strings are frequently made up of characters. They are suitable for storing human-readable data, like
sentences, or lists of alphabetical data, like the nucleic acid sequences of DNA. In computer programming,

2
UNIT 03: Strings JGI JAIN
DEEMED-TO-BE UNIVERSITY

a string is usually an arrangement of characters, either as a literal constant or as some generous of


variable. If we declare as character arrays, they are reserved as the Arrays. For instance, if SmplStr []
is an auto variable then its content is stored in stack segment, whereas if it’s a static or global variable
then reserved in data segment.
In prorammeming language, a string can be referred to by either using a character pointer or by using
a character array is described below:
zz Strings as character arrays: String is a sequence of characters that are treated as a single data item
and terminated by a null character. For example: char Smplstr[4] = "DfD"; /*One space additional for
string terminator*/ /* OR */char SmplStr[4] = {'D', 'f', 'D', '\0'}; /*Here '\0' is the string terminator */.

D
zz Using character pointers: Strings are stored in two different ways using character pointer is
described in steps below:

E
Step 1: Reading string alone in a shared segment: If a string is directly allocated to a pointer, most

V
compilers store it in a read-only block, mostly in data segment which is shared between functions.
char *SmplStr = "DfD;In the above case, “DfD” is reserved in a shared read-only memory location,

R
but pointer SmplStr is reserved in a read-write memory location. We can make the SmplStr to
point to any value but cannot modify the value currently in Smplstr. So such strings should be used

E
only when we don’t wish to change the string later anywhere in the programme.
Step 2: Strings are dynamically allocated in heap segment: Strings can also be reserved as other
S
dynamically allocated objects and can be shared between multiple functions is given below:
E
Char *SmplStr;
int size = 4; /*One space additional for '\0'*/
R
SmplStr = (char *)malloc(sizeof(char)*size);
*(SmplStr+0) = 'D';
*(SmplStr +1) = 'f';
T

*(SmplStr +2) = 'D';


H

*(SmplStr +3) = '\0';

3.5 STrINg UTILITy fUNcTIONS


IG

String operations are shared to all kind of programming. Java has many in manufactured operations
maintained by String class. String functions in java contain substring trim and more. However, there
are a insufficient more things we do on a systematic basis and can be reused.
R

The string class is vast and consists of multiple constructors, member functions, and operators
Y

Programmer may use the following features is as follows:


Generating the string objects
P

zz

Scanning string objects from the keyboard


O

zz

zz Showing string objects on the screen


C

zz Searching a substring within a string


zz Mutating string
zz Concatenating multiple strings
zz Constrating multiple strings
zz Fetching the characters from a string
zz Acquiring the length of a string

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

3.6 STrINg OPeraTIONS


We can define Strings as an array composed of characters. A character array is different from the
string due to the fact that string always ends with a special character ‘\0’.
An elementary form of comparison of strings is achieved using the strcmp() function. It has two strings
as arguments and retains a negative value, less than zero if the first string is lexically less than the
second string. A positive value, greater than zero is retained if the first string is lexically greater than
the adjoining second string. Zero is returned, if the two strings are found lexicographically equal.
Nowadays, the elementary string comparison process, as discussed above is generally unacceptable

D
while lists of strings are sorted. More sophisticated algorithms capable of producing lists in dictionary
sorted order are under utilisation. Such algorithms can also fix problems encountered, such as in

E
strcmp() function, the string “Beta2” is considered greater than “Beta12”,as ‘2’ comes after ‘1’ in the
character set. What we are suggesting is that the strcmp() alone should not be considered for string

V
sorting in any mercantile or professional code.

R
The strcmp() function contrasts the string pointed to by s1 with the string pointed to by s2. The sign of
a returned non-zero value is determined by the sign of the difference among the values of the first pair

E
of bytes (both declared as type unsigned char) which varies in the strings being differentiated. Upon
termination, strcmp() retains an integer value which is either greater than, or equal to, or less than 0,
based on the comparison of the strings S1 and S2, respectively.
S
E
Since, it is not realistically useful to compare String pointers amongst themselves unless they are being
compared within the same array, the function strcmp() lexicographically contrast the strings which the
R
two pointers point to.
The functions used in strings are described in details below:
T

zz The Strcmp () function: It is used to associate two strings str1 and str2. If two strings are similar then
strcmp() returns 0, otherwise, it returns a non-zero value. This function associates strings character
H

by character by means of ASCII value of the characters. The assessment stops when either end of the
string is got or equivalent characters are not same.
IG

The following algorithm represents the Strmcmp() function is as follows:


#include <stdio.h>
R

#include <string.h>
int main () {
char STR1[18];
Y

char STR2[18];
P

int ret;
strcpy(STR1, "abcdef");
O

strcpy(STR2, "ABCDEF");
ret = strcmp(STR1, STR2);
C

if(ret < 0) {
printf("str1 is less than str2");
} else if(ret > 0) {
printf("str2 is less than str1");
} else {
printf("str1 is equal to str2");
}

4
UNIT 03: Strings JGI JAIN
DEEMED-TO-BE UNIVERSITY

return(0);
}
The running output of Strcmp() function is given below:
Str2 is less than Str1
zz The strcpy () function: The strcpy () function copies the string pointed by basis (including the null
character) to the endpoint. The strcpy () function also revenues the copied string. The strcpy ()
function is well-defined in the string.h header file.
The following algorithm represents the strcpy() function is as follows:

D
#include <stdio.h>
#include <string.h>

E
int main( )
{

V
char source[ ] = "home sweet home" ;
char target[20]= "" ;

R
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;

E
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;

}
return 0;
S
E
The running output of the strcpy()function is given below:
R
Source string = home sweet home
Target string =
T

Target string after strcpy( ) = home sweet home


The strlen function: The strlen() function computes the total bytes in the string pointed by strpntr,
H

zz
excluding the ending null byte. It returns the total count of the bytes in the string. The occurrence of
error is not indicated by any value.
IG

The following algorithm represents the Strlen() function is as follows:


#include <stdio.h>
R

#include <string.h>
int main () {
char STR[70];
Y

int len;
P

strcpy(STR, "This is [Link]");


len = strlen(STR);
O

printf("Length of |%s| is |%d|\n", STR, len);


return(0);
C

}
The running output of the strlen()function is give below:
Length of |This is [Link]| is |26|
zz The strncat function: The strncat() function appends only n bytes (The null byte and bytes following
it are not attached) from the array being pointed by strpntr2 to the end of the string pointed
by strpntr1. The first byte of strpntr2 overwrites the null byte present at the end of strpntr1. An
ending null byte is always attached to the result. If copying happens among the overlap objects, the
respective behaviour remains undefined. The function retains strpntr1.

5
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The following algorithm represents the strncat function is as follows:


#include <stdio.h>
#include <string.h>
int main () {
char src[60], destination[60];
strcpy(src, "Hardwork ");
strcpy(destination, " truth of life is");
strncat(destination, src, 15);
printf("Final destination string : |%s|", destination);

D
return(0);
}

E
The running output of strncat function is given below:
Final destination string: | truth of life isHardwork |

V
3.7 PaTTerN recOgNITION aLgOrIThMS

R
Pattern recognition confronts the problem of searching all occurrences of a specific pattern string in

E
a given text string. Such Algorithms have multiple realistic applications. Innovative data structures
are introduced and former data structures are upgraded to provide more effective solutions to pattern
recognition problems.
S
E
The following algorithm represent pattern reorganization is as follows:
#include<stdio.h>
R
int main()
{
int row, J;
T

for (row=1; row<=4; row++)


{
H

for (J=1; J<=4; J++)


{
IG

printf("12345");
}
printf("\n");
R

}
return 0;
Y

}
The running output of the pattern recognition is given below:
P

12345123451234512345
O

12345123451234512345
12345123451234512345
C

12345123451234512345

Conclusion 3.8 cONcLUSION

zz A String is referred as a data type to be used in programming, By data type we mean an integer type
or a floating point type.
zz String utility functions are shared to all kind of programming.

6
UNIT 03: Strings JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Pattern recognition confronts the problem of searching all occurrences of a specific pattern string
in a given text string.
zz String operation can define Strings as an array composed of characters.
zz String storing human-readable data, like sentences, or lists of alphabetical data, and it is frequently
made up of characters.

3.9 gLOSSary

D
zz String: It is used to represent sequence of characters.
zz Pattern: It is used to represent function or algorithms.

E
zz concat: This function used to joining two strings.

V
zz cmp: This function used to compare strings.
zz String constant: It refers to zero or more characters mentioned in double quotation marks.

R
E
3.10 SeLf-aSSeSSMeNT QUeSTIONS

a. Multiple choice Questions


S
E
1. What is a string?
R
a. String is array of integers with 0 as last element of array.
b. String is an array of characters with null character as first element of array.
c. String is array of characters with null character as last element of array.
T

d. String is a new data type.


H

2. Select a right statement about C string.


IG

char rdt[]="Hello..!";
a. String size is not mentioned
b. String cannot have special characters
R

c. Rdt has no null character at the end


d. Character array, rdt is a string
Y

3. What is the right output of the below programme?


P

int main()
O

{
char ary[]="Hitech life";
printf("%s",ary);
C

return 0;
}
a. Hitech
b. Hitech life
c. H
d. Compiler error

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

4. How do you convert this char array to string?


char str[]={'s', 'k', 'y''};
a. str[3] = 0;
b. str[53= ‘\0’
c. str[]={‘s’, ‘k’, ‘y’,’\0’};
d. All of these
5. What is the name of elements existing in patterns?

D
a. Variables
b. Patterns

E
c. Pattern variables

V
d. Pattern components
6. Which of the following is a sequence of characters that are treated as a single data item and

R
terminated by a null character?

E
a. Array
b. String
c. Operands
S
E
d. None of these
R
7. What kind of return-type used in string operations?
a. void only
T

b. void and (char *) only


c. int only
H

d. void, int and (char *) only


IG

8. The _______________ operator allows you to use pattern matching characters to define whether
one string is equal to another String.
a. Like
R

b. String Match
Y

c. Match
d. Pattern
P

9. Which operator is used in a pattern to represents one character only?


O

a. ?
C

b. *
c. #
d. **
10. Determine the value which is return by Like operator.
a. Float
b. Boolean

8
UNIT 03: Strings JGI JAINDEEMED-TO-BE UNIVERSITY

c. Integer
d. Float

B. essay Type Questions


1. A data type we mean an integer type or a floating point type, however, it represents text instead of
numbers. What is a String?
2. Strings are frequently made up of characters. They are suitable for storing human-readable data,
like sentences, or lists of alphabetical data. Describe the concept of storing data in string.

D
3. String operations are shared to all kind of programming. Java has many in manufactured operations
maintained by String class. Explain the importance of Utility functions of string.

E
4. We can define Strings as an array composed of characters. A character array is different from the
string due to the fact that string always ends with a special character ‘\0’. Determine the significance

V
of string operations.

R
5. The problem of searching all occurrences of a specific pattern string in a given text string. Elaborate
the Pattern recognition in string.

E
3.11 aNSwerS aNd hINTS fOr SeLf-aSSeSSMeNT QUeSTIONS
S
E
a. answer to Multiple choice Questions
R
Q. No. answer
1. c. String is array of characters with null character as last element of array.
T

2. d. Character array, rdt is a string


H

3. b. Hitech life
4. d. All of these
IG

5. c. Pattern variables
6. b. String
R

7. d. void, int and (char *) only


8. a. Like
Y

9. a. ?
P

10. b. Boolean
O

B. hints for essay Type Questions


1. A String is referred as a data type to be used in programming, by data type we mean an integer
C

type or a floating point type, however, it represents text instead of numbers. It includes a set of
characters and may even have spaces and numbers. Refer to Section Strings
2. Strings are frequently made up of characters. They are suitable for storing human-readable data,
like sentences, or lists of alphabetical data, like the nucleic acid sequences of DNA. In computer
programming, a string is usually an arrangement of characters, either as a literal constant or as
some generous of variable. Refer to Section Storing Data in Strings

9
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

3. String operations are shared to all kind of programming. Java has many in manufactured operations
maintained by String class. String functions in java contain substring trim and more. However,
there are a insufficient more things we do on a systematic basis and can be reused. Refer to Section
String Utility Functions
4. An elementary form of comparison of strings is achieved using the strcmp() function. It has two
strings as arguments and retains a negative value, less than zero if the first string is lexically less than
the second string. A positive value, greater than zero is retained if the first string is lexically greater
than the adjoining second string. Zero is returned, if the two strings are found lexicographically
equal. Refer to Section Strings Operations

D
5. Pattern recognition confronts the problem of searching all occurrences of a specific pattern string in
a given text string. Such Algorithms have multiple realistic applications. Innovative data structures

E
are introduced and former data structures are upgraded to provide more effective solutions to
pattern recognition problems. Refer to Section Pattern Recognition Algorithms

V
R
@ 3.12 POST-UNIT readINg MaTerIaL

E
zz [Link]
[Link]
zz

S
E
3.13 TOPIcS fOr dIScUSSION fOrUMS
R
zz Discuss with your friends and classmates on the concept of strings and the importance of its
operations. Also discuss on the utility function of string and Pattern recognition of strings in real
T

life environment.
H
IG
R
Y
P
O
C

10
UNIT

04

D
E
Recursion

V
R
E
Names of Sub-Units S
E
Introduction to Recursion, Programming Techniques Implementing Recursion, Types of Recursion
and Relevance of Recursion.
R

Overview
T
H

This unit begins by discussing about the concept of recursion. Next, the unit discusses the programming
techniques of implementing recursion. Further the unit explains the types of recursion. Towards the
IG

end, the unit discusses the relevance of recursion.


R

Learning Objectives
Y

In this unit, you will learn to:


Discuss the concept of recursion
P

a Explain the concept of programming techniques of implementing recursion


O

a Describe the types of recursion


Explain the significance of relevance of recursion
C

a Discuss the programming techniques of recursion


JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit you would:


a Evaluate the concept of recursion
a Assess the concept of relevance of recursion
a Evaluate the importance of recursion
a Determine the significance of programming techniques of implementing recursion

D
a Explore the types of recursion

E
Pre-Unit Preparatory Material

V
a [Link]

R
4.1 INTROdUcTION TO RecURSION

E
Recursion is a procedure in which a function makes a call to itself moreover in a direct mode or in an
S
indirect mode; the respective function is known as recursive function. We can solve definite complex
problems easily using recursive algorithm method. Towers of Hanoi (TOH), Tree Traversals, DFS of
E
Graph, etc. certain examples to which recursive algorithm approach can be applied for easier solutions.
An obvious question might arise in mind that why can’t we go for iteration instead of using recursion in
R
such scenarios? This is mainly because, recursion expand the readability of the program and with the
modern advanced CPU systems, implementing recursion is much well-organized than iterations.
T

4.2 MaTheMaTIcaL eLUcIdaTION


H

Let’s try to figure out solutions for a program where we have to calculate the sum of first n natural
numbers. Several possible solutions do exist, and the most elementary among them will be to add all the
IG

numbers from 1 to n, the corresponding function will resemble something is given as:
zz Simple method: Adding up all the numbers individually. The function of simple method is as follows:
R

F (n) = (1 + 2 + 3 +……..+ n).


zz Recursive method: Adding all the numbers recursively. The function of recursive method is as
Y

follows:
P

F (n) = 1 n=1
O

F (n) = n + f (n-1) n>1


Both the approaches are different from each other in a way that in the second approach off recursive
C

method. The function f has been called inside the same function. This process is termed as Recursion
and the function implementing recursion process is known as recursive function. Recursion acts as a
great reliever to the programmers for coding complex problems efficiently.

4.3 TyPeS Of RecURSION


Recursion occurs when a thing is well-defined in terms of itself or of its type. Recursion is used in a
change of disciplines ranging from linguistics to logic. The most mutual application of recursion is

2
UNIT 04: Recursion JGI JAIN
DEEMED-TO-BE UNIVERSITY

in mathematics and computer science, where a function existence defined is applied within its own
description. While this apparently defines an infinite number of occurrences (function values), it is often
done in such a way that no infinite loop or infinite chain of references can occur. There are 4 types of
recursion which is described below:
zz direct Recursion: As in the name itself, direct recursion is a single step recursion case where the
function calls itself.
zz Indirect Recursion: In simple words, indirect recursion depends on another function. It contains
two functions that depend on one another.
Tail / Bottom Recursion: Tail recursion is a method of linear recursion. In tail recursion, the recursive

D
zz
call is the previous thing the function does. Often, the value of the recursive call is returned.

E
zz Linear and Tree Recursion: Depending on the structure the recursive function calls take, It is linearly
recursive when, the incomplete operations do not involve another recursive call to the function. Our

V
Factorial recursive function is linearly recursive as it only contains multiplying the returned values
and no further calls to function.

R
Function is an addressed as direct recursive if it makes a call to itself, while indirect recursive function
calls another function in its scope. For example, consider two functions Func_Visit and Rest (), where

E
Func_Visit make so call to Rest () either directly or indirectly. An example of implementation of direct
recursion in C++ is given below:
#include <iostream> S
E
using namespace std;
// Here is to calculate square of a number
R
int sq(int X)
{
// Here we apply base case
T

if (X == 0)
H

{
return X;
}
IG

else
{
return sq(X-1) + (2*X) - 1;
R

}
}
Y

int main() {
// implementiing square functions
P

int input=40;
O

cout << input<<”^8 = “<<sq(input);


return 0;
}
C

The output of direct recursive function in C++ is as follows:


40^8 = 1600

4.4 PROgRaMMINg TechNIqUeS IMPLeMeNTINg RecURSION


A coding approach including the usage of a subroutine, procedure, function or an algorithm, in which
a function calls itself repeatedly until a terminating condition is encountered which is also called as the
critical step allowing the processing of successive iterations till the critical step is met.

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

In order to solve a given complex problem, divide it into multiple subproblems of smaller instances,
solve them individually, and then use the solutions to solve the native problem.
For example, while calculating n!n!n!,we divided the problem into the subproblem aiming at calculating
the factorial of the immediate preceding smaller number, i.e. finding n(n-1)!n(n−1)!n(n-1)!, Which act
as the smaller instances of the native problem, followed by utilising the obtained solutions of the
subproblem to find n!. The solution can also be achieved through recursion properties. A recursive
function can run till infinity surrounded in a loop. To avoid from such situations, a recursive function
must have the following two properties:
Base criteria: One base criteria or terminating condition must exist, such that, when this criteria is

D
zz
satisfied, the function restricts from calling itself recursively.
Progressive approach: The recursive calls to the function should proceed in a manner so that during

E
zz
each recursive call the recursive function comes closer to the terminating condition or base criteria.

V
4.5 IMPLeMeNTaTION Of RecURSION

R
Recursion is frequently executed through the data structures called stacks in numerous programming
languages. In general during the function calls, the caller function passes on the execution control

E
to caller (which is a function being called), and the process involves exchange of data from the caller
function to the callee, which conveys that the caller function must temporarily halt its execution and
S
restart later upon the return of the program execution control from the caller function. Figure 1, shows
E
how to implement the recursion functions. This activation record holds the data regarding the local
variables, formal parameters, return address and all the data transferred to the caller function. An
R
example of implementing recursion is shown in Figure 1:
T

f(n)
H

f(n-1)
Recursive Function

IG

f(n-2)
f(n-2)
R

f(n-1)
Y

f(n) Activation
P

Record
O

Call Stack

figure 1: Implementation of Recursion


C

4.5.1 factorial
Factorial is a multiplication of all integers smaller than or equal to n of a non-negative integer.
In general, the for loop and while loop is used for finding the factorial of a given number. However we
can also use the technique of recursion to evaluate the factorial of a number. To solve the problem of
finding n!, Split them into smaller instances as n! = n * (n-1)!. The Factorial of a number n is calculated
as 1 * 2 * … * (n-1) * n and it’s indicated by n!.

4
UNIT 04: Recursion JGI JAIN
DEEMED-TO-BE UNIVERSITY

For example: Factorial of 6 = 6! = 6*5*4*3*2*1 or 1*2*3*4*5*6


We are aware of the fact that
5! = 5*4*3*2*1
We can write it as,
5! = 5 * 4 * 3!
In a similar way,

D
4! = 4 * 3 * 2!
3! = 3 * 2 * 1!

E
1! = 1 * 0!

V
0! = 1

R
Generalizing the above, leads us to the fact that we can compute the factorial of a given number N as
the product of N and the factorial of N -1.

E
n! = n * (n-1)!
S
Now, the problem of calculating the factorial of n-1, is identical to the process of finding the factorial of
E
n, which is less than the value of n! Hence we have figured out the solution to the problem of finding the
factorial following a recursive approach. We are aware of the fact that the 0!=1 and 1!=1, which can act
R
as the base criteria or the terminating condition. The base case or terminating condition for evaluating
factorial is as follows:
factorial (0) = 1
T

Or,
H

factorial (1) = 1
Formula for calculating the factorial,
IG

factorial (n) = n * factorial(n-1)


Following algorithm shows calculation of factorial using recursion in C++ is as follows:
#include <iostream>
R

using namespace std;


int fact(int N) {
Y

if ((N==0)||(N==1))
return 1;
P

else
return N*fact(N-1);
O

}
int main() {
C

int n = 7;
cout<<”Factorial of “<<n<<” is “<<fact(n);
return 0;
}
The output of the given C++ program is as follows:
Factorial of 7 is 5040

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

4.5.2 highest common factor (hcf)


To find the Highest Common Factor (HCF) or the Greatest Common Divisor (GCD), of the given numbers,
it is required to list all the prime factors, of the number, find out their intersection i.e. common prime
factors among them, and retain the elements of the intersection for all the common prime factors.
The Euclidean algorithm provides an efficient approach to solve for the HCF or the GCD of the given
numbers. The main fact to be considered here is that the HCF of two numbers does not modify if the
smaller number is subtracted from the larger number.
The following C++ program represents HCF of two numbers:

D
#include <iostream>
using namespace std;

E
int GCD(int a, int b){

V
if (a == 0)
return b;

R
if (b == 0)
return a;

E
if (a == b)
return a;
if (a > b)
return GCD(a-b, b); S
E
return GCD(a, b-a);
}
R
int main(){
int a = 98, b = 14;
cout<<”GCD of “<<a<<” and “<<b<<” is “<<GCD(a, b);
T

return 0;
}
H

The output of the given C++ program is as follows:


IG

GCD of 98 and 14 is 14

4.5.3 fibonacci Sequence


R

In Fibonacci series the sequence of the numbers is generated through summation of the preceding two
numbers of the sequence. The initial two terms are 0 and 1. The subsequent terms of the series are
Y

formed by adding the preceding two terms.


P

The following C++ program shows the Fibonacci sequence:


#include <iostream>
O

using namespace std;


int fib(int x) {
C

if((x==1)||(x==0)) {
return(x);
}else {
return(fib(x-1)+fib(x-2));
}
}
int main() {
int x , i=0;

6
UNIT 04: Recursion JGI JAIN
DEEMED-TO-BE UNIVERSITY

cout << “\nEnter the value to found the Fibonacci series: “; cin >>
x;
cout << “\The Fibonacci Series is “;
while(i < x) {
cout << “ “ << fib(i);
i++;
}
return 0;
}

D
The output of the given C++ program is as follows:
Enter the value to found the Fibonacci series: 6

E
The Fibonacci Series is: 0 1 1 2 3 5

V
4.6 TOweRS Of haNOI
In the puzzle of Towers of Hanoi, we are provided with a platform having three pegs installed namely a,

R
b and c. Peg a contains the stack of N discs, of varying sizes, arranged in such a way that the smallest
is at the top and the largest among them is at the bottom, in between are the disks lead in decreasing

E
order of their sizes, one above the other. The puzzle requires us to move all the disks from peg a to c,
transferring one disc at a time, so that a larger disc is never placed on the top of a smaller disc. The
S
figure below gives us an idea of the starting and the ending position of the discs with the value of n = 4.
E
Let’s give an example of moving four disks as shown in Figure 2:
R
T
H
IG

a b c a b c
(Source) (Spare) (dest) (Source) (Spare) (dest)
R

figure 2: Tower of hanoi


Y

In the above, puzzle the total number of moves needed to transfer the n number of discs is 2^n-1. So, for
the above problem of transferring four discs from peg to peg c requires 15 steps (2^4-1). However, if we
P

follow a recursive approach then we can generalize the problem into three different steps:
O

Step 1: Transfer disk 3 and all other smaller discs from peg a to peg b using the spare peg c, which can be
achieved to the recursive calls of the same procedure with three discs, after which all the smaller discs
C

will be moved to Peg b.


Step 2: Transfer the disc 4 from peg A to peg C, following which we will have all the three smaller discs
on peg b and the fourth disc moved to peg c, and peg a will be left empty.
Step 3: Transfer this disc 3 and the remaining smaller discs from peg b to peg c with a spare peg. This
transfer process can be achieved recursively by making a call to the procedure of transferring three
disks with varying source and destination. Thus, will be able to move all the four discs from peg a to
peg c.

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The pseudocode of Tower of Hanoi is as follows:


Tower (disk, source, inter, dest)
IF disk is equal 1, THEN
Move disk from source to dest
ELSE
Tower (disk - 1, source, dest, intermediate) // Step 1
Move disk from source to dest // Step 2
Tower (disk - 1, intermediate, source, dest) // Step 3
END IF

D
END

E
4.7 ackeRMaN’S fUNcTION

V
One of the simplest instances of an explicit total function which is calculable but not primordial recursive
is Ackermann function. This function acts as a refutation to the general belief persisting in the early

R
1900’s, that all the calculable function were primordial recursive.

E
The Ackermann function is the simplest example of an unambiguous total function which is assessable
but not primitive recursive, if a counter example to the belief in the early 1900’s that every assessable

S
function was also primitive recursive. It expands swifter when compared to a single or multiple
exponential functions.
E
The Ackerman algorithm in C++ is as follows:
R
#include <iostream>
#include <iomanip>
unsigned long long ack(unsigned long long m, unsigned long long n);
T

int main(){
int M {2};
H

int N {2};
// Create array dynamically to hold values
IG

unsigned long long** ackerman_values = new unsigned long long*[M + 1];


// Pointer to array of arrays of unsigned long elements
for (int i = {}; i <= M; ++i)
R

ackerman_values[i] = new unsigned long long[N + 1];


// Store values in the array
Y

for (int i = {}; i <= M; ++i)


for (int j = {}; j <= N; ++j)
P

ackerman_values[i][j] = ack(i, j);


for (int i {}; i <= M; i++)
O

{
std::cout << std::endl;
C

for (int j {}; j <= N; ++j){


std::cout << std::setw(12) << ackerman_values[i][j];
}
}
std::cout << std::endl;
for (int i {}; i < M + 1; ++i){
delete[] ackerman_values[i];
}

8
UNIT 04: Recursion JGI JAIN
DEEMED-TO-BE UNIVERSITY

delete ackerman_values;
}
unsigned long long ack(unsigned long long m, unsigned long long n){
if (m == 0ULL)
return n + 1;
if (n == 0ULL)
return ack(m - 1, 1);
return ack(m - 1, ack(m, n - 1));
}

D
The output of given C++ code is as follows:
1 2 3

E
2 3 4
3 5 7

V
4.8 cONcLUSION

R
Conclusion

zz Recursion is a procedure in which a function makes a call to itself moreover in a direct mode or in

E
an indirect mode.
zz
change of disciplines ranging from linguistics to logic.S
Recursion occurs when a thing is well-defined in terms of itself or of its type. Recursion is used in a
E
zz A coding approach including the usage of a subroutine, procedure, function or an algorithm, in
which a function calls itself repeatedly.
R

zz Factorial is a multiplication of all integers smaller than or equal to n of a non-negative integer.


zz In Fibonacci series the sequence of the numbers is generated through summation of the preceding
T

two numbers of the sequence.


H

zz Towers of Hanoi, is a mathematical puzzle in which we have three towers called (pegs) namely a, b
and c.
IG

zz One of the simplest instances of an explicit total function which is calculable but not primordial
recursive is Ackermann function.
R

4.9 gLOSSaRy
Y

zz Recursion: It is a procedure in which a function makes a call to itself moreover in a direct mode or
in an indirect mode.
P

zz fibonacci: Number sequence in which each number (Fibonacci number) is gained from the addition
O

of the two previous numbers. The first seven terms of the series are: 0, 1, 1, 2, 3, 5, 8
zz Towers of hanoi: A mathematical puzzle requiring the movement of N disks from peg a to c using
C

a spare peg b.
zz ackerman’s functions: The Ackermann function is the simplest example of an unambiguous total
function which is assessable but not primitive recursive.
zz highest common factor: To find the Highest Common Factor (HCF) or the Greatest Common Divisor
(GCD) of the given numbers, it is required to list all the prime factors of the number.

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

4.10 SeLf-aSSeSSMeNT qUeSTIONS

a. Multiple choice questions


1. In the process of recursion, the resolving problem relies on ____________.
a. Bigger occurrences of multiple problems
b. Bigger occurrences of the identical problem

D
c. Minor occurrences of the identical problem
d. Minor occurrences of multiple problems

E
2. Which among the following recursion is not applicable?

V
a. The Factorial of a positive number
b. Kth term of the Fibonacci series

R
c. Size of a string

E
d. Problems excluding the base criteria or termination condition
3. Recursion resembles which of the statements below?
a. The Switch construct S
E
b. Looping constructs
R
c. If-else statements
d. If else if case
4. In recursion, the criteria which a recursive function ceases from repeated self calls is ____________.
T

a. Worst case
H

b. Best case
IG

c. Base case
d. All of these
5. Which statement is true for the given algorithm?
R

Void Func_Rcrsv()
{
Y

Func_Rcrsv();
P

}
int main()
O

{
Func_Rcrsv ();
C

return 0;
}
a. The program runs without an output.
b. The program runs with random output.
c. The program ends up displaying error during compilation.
d. The program will stop because of encountered overflow condition in stack.

10
UNIT 04: Recursion JGI JAIN
DEEMED-TO-BE UNIVERSITY

6. What is the output of the given algorithm?


#include<cstdio>
void Func_Rcrsv(int n)
{
if(n == 0)
return;
printf(“%d “,n);
Func_Rcrsv (n-1);
}

D
int main()
{

E
Func_Rcrsv(10);
return 0;

V
}
a. 10 9 8 … 1

R
b. 10 9 8 … 1 0
c. 1

E
d. 10
7. S
What is the termination condition for the following code?
E
void Func_Rcrsv(int n)
{
R
if(n == 0)
return;
printf(“%d “,n);
T

Func_Rcrsv (n-1);
}
H

int main()
{
IG

Func_Rcrsv(10);
return 0;
}
R

a. return
b. Print (“%d “, v)
Y

c. If (v == 0)
P

d. Func_Rcrsv (v-1)
O

8. Choose the number of calls made by recursive function makes:


void Func_Rcrsv (int v)
C

{
if(v == 0)
return;
printf(“%d “,v);
Func_Rcrsv (v-1);
}
int main()

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

{
Func_Rcrsv (10);
return 0;
}
a. 8 b. 2
c. 11 d. 10
9. What is the output of the following program?
#include<cstdio>

D
void Func_Rcrsv (int v)
{
if(v == 0)

E
return;
Func_Rcrsv (v-1);

V
printf(“%d “,v);
}

R
int main()
{

E
Func_Rcrsv (9);

}
return (0);
S
E
a. Displays the numbers ranging from 9 to 1
b. Displays the numbers ranging from 9 to 0
R

c. Displays the numbers ranging from 1 to 9


d. Displays the numbers ranging from 0 to 9
T

10. Choose the correct statement about the context of recursion.


H

a. Recursion is more desirable compared to iteration


b. Recursion requires larger memory than iteration.
IG

c. Recursion consumes lower memory than iteration


d. Iteration is more desirable compared to recursion
R

B. essay Type questions


Y

1. A function makes a call to itself moreover in a direct mode or in an indirect mode; the respective
function is known as recursive function. What is a Recursion?
P

2. Recursion occurs when a thing is well-defined in terms of itself or of its type. Recursion is used in a
O

change of disciplines ranging from linguistics to logic. Describe the types of recursion.
3. A function calls itself repeatedly until a terminating condition is encountered which is also called as
C

the critical step. Explain the programming implementing techniques in recursion.


4. We are provided with a platform having three pegs installed namely a, b and c. Peg a contains the
stack of N discs, of varying sizes, arranged in such a way that the smallest is at the top. Determine
the concept of Tower of Hanoi.
5. This function acts as a refutation to the general belief persisting in the early 1900’s, that all the
calculable function was primordial recursive. Define Ackerman’s functions.

12
UNIT 04: Recursion JGI JAIN
DEEMED-TO-BE UNIVERSITY

4.11 aNSweRS aNd hINTS fOR SeLf-aSSeSSMeNT qUeSTIONS

a. answers to Multiple choice questions

q. No. answer
1. c. Minor occurrences of the identical problem
2. d. Problems excluding the base criteria or termination condition

D
3. b. Looping constructs
4. d. Base case

E
5. d. The program will stop because of encountered overflow condition in stack

V
6. a. 10 9 8….1

R
7. c. if(v==0)
8. c. 11

E
9. c. displays the numbers ranging from 1 to 9
10. b.
S
Recursion requires larger memory than iteration
E
B. hints for essay Type questions
1. Recursion is a procedure in which a function makes a call to itself moreover in a direct mode or in an
R

indirect mode; the respective function is known as recursive function. We can solve definite complex
problems easily using recursive algorithm method. Towers of Hanoi (TOH), Tree Traversals, DFS of
Graph, etc. Refer to Section Introduction of Recursion
T

2. Recursion occurs when a thing is well-defined in terms of itself or of its type. Recursion is used in a
H

change of disciplines ranging from linguistics to logic. The most mutual application of recursion is
in mathematics and computer science, where a function existence defined is applied within its own
IG

description. Refer to Section Types of Recursion


3. A coding approach including the usage of a subroutine, procedure, function or an algorithm, in
which a function calls itself repeatedly until a terminating condition is encountered which is also
R

called as the critical step allowing the processing of successive iterations till the critical step is met.
Refer to Section Programming Techniques Implementing Recursion
Y

4. In the puzzle of Towers of Hanoi, we are provided with a platform having three pegs installed namely
P

a, b and c. Peg a contains the stack of N discs, of varying sizes, arranged in such a way that the
smallest is at the top and the largest among them is at the bottom, in between are the disks lead in
O

decreasing order of their sizes, one above the other. Refer to Section Tower of Hanoi
5. The Ackermann function is the simplest example of an unambiguous total function which is
C

assessable but not primitive recursive, if a counter example to the belief in the early 1900’s that
every assessable function was also primitive recursive. Refer to Section Ackerman’s Functions

@ 4.12 POST-UNIT ReadINg MaTeRIaL

zz [Link]
zz [Link]

13
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

4.13 TOPIcS fOR dIScUSSION fORUMS

zz Discuss with your friends about the topics of Recursion and its types. Also make discussion on
programming techniques implementing recursion. Tower of Hanoi which is a mathematical puzzle,
is a very interesting topic to disucss with your friends and also on Ackerman’s functions.

D
E
V
R
E
S
E
R
T
H
IG
R
Y
P
O
C

14
UNIT

05

D
E
Stacks

V
R
E
Names of Sub-Units S
E
What are Stacks? Operations of Stack, Representing Stack Using Static Arrays, Using Dynamic Array
R
for Representing Stack, Applications of Stack.
T

Overview
H

This unit begins by discussing about the concept of stacks. Next, the unit discusses the operations
of stack, representing stack using static arrays. Further the unit explains the dynamic array for
IG

representing stack. Towards the end, the unit discusses the application of stack.
R

Learning Objectives
Y

In this unit, you will learn to:


P

a Discuss the concept of stack


a Explain the concept of operations of stack
O

a Describe the representation of stack using static arrays


C

a Explain the significance of dynamic array for representing stack


a Discuss the applications of stack
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of stack
a Assess the concept of using dynamic array for representing stack
a Evaluate the importance of operations of stack
a Determine the significance of representing stack using static arrays

D
a Explore the applications of stack

E
Pre-Unit Preparatory Material

V
a [Link]

R
5.1 INTrOdUcTION

E
A stack is an abstract structure containing a set of homogeneous components and is based on the
S
principle of Last In First Out (LIFO). It is a usually used abstract data type with two major operations,
namely push and pop. Push and pop are carried out on the topmost element, which is the item best
E
recently added to the stack. The data structure stack denotes an Abstract Data Type (ADT), generally
used in several programming languages. For example: A pile of plates or a deck of cards.
R

The stack is generally used in converting and assessing expressions in Polish notations, i.e. Infix, Prefix
Postfix. In case of arrays and linked lists, these two agree programmers to insert and delete components
T

from any place within the list, i.e., from the beginning or the end or even from the middle also. But in
computer programming and expansion, there may raise some situations where insertion and deletion
H

want only at one end decline at the beginning or end of the list. The stack is a linear data structure, and
all the insertion and deletion of its values are complete in the same end which is called the top of the
IG

stack. Let us assume, take the real-life example of a stack of plates or a pile of books etc. As the item in
this form of data structure can be detached or added from the top only which means the last item to be
added to the stack is the first item to be removed. So you can say that the stack follows the Last In First
R

Out (LIFO) structure.


Y

5.2 OPeraTIONS Of STack


P

A stack has two simple services such as: PUSH, POP. The PUSH methods adds an element at the top of
the stack whereas, the POP method eliminates the element from the top of the stack. The PEEK method
O

returns the value to the topmost element of the stack. Following are the two basic operations of stack
are as follows:
C

zz PUSH (): Inserting an element on the stack


zz POP (): Fetching an element from the stack

The following operations help us to know the status of the stack is as follows:
zz Peek (): Access the topmost element of the stack, without deleting it
zz Is full (): Check whether the stack is completely occupied
zz Is empty (): Check whether stack is vacant

2
UNIT 05: Stacks JGI JAIN
DEEMED-TO-BE UNIVERSITY

5.2.1 PUSH Operation


The PUSH operation is complete to insert an element into the stack. The new element is added at the
highest position of the stack. Though, before inserting the value in the stack, we want to first check
if TOP=MAX–1, since if this is the circumstance, then this stack is full and no longer insertions can be
made. A pointer is always maintained, which points to the last inserted data on the stack. This pointer
is addressed as the top. The top pointer retains the value of the stack’s top without deleting it. PUSH
operation involves following steps are as follows:
zz Step 1: Inspect whether the stack is occupied.

D
zz Step 2: If the stack is occupied, display an error and exit.
zz Step 3: If the stack is not entirely occupied then it increases to the top point to the next empty space.

E
zz Step 4: Insert the data element to the available location, where it is pointed by the top pointer.

V
The following C++ programme shows the implementation of PUSH operation:
#include <iostream>

R
#include <stack>
using namespace std;

E
int main() {
stack<int> stack;
[Link](20); S
E
[Link](40);
[Link](60);
R
[Link](80);
while (![Link]())
{
T

cout << ' ' << [Link]();


[Link]();
H

}
}
IG

The output of the given C++ programme is as follows:


80 60 40 20
R

5.2.2 P0P Operation


Y

Fetching the data element from the stack, is known as a P0P(). During this operation, if implemented
via arrays, the data element is not deleted, instead the top position is decreased to a lower position in
P

the stack pointing to the subsequent value. However, in linked-list implementation, POP () physically
deletes the data element the deallocating the memory space. A POP operation has the following steps is
O

as follows:
Step 1: Inspect whether the stack is Vacant.
C

Step 2: If the stack is vacant, display an error and exit.


Step 3: If the stack is occupied, fetch the data element being pointed by the top pointer.
Step 4: Reduce the value of top by 1.

The following C++ programme is used to determine the implementation of POP () function by insertion
of simple integer values:
#include <iostream>

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

#include <stack>
int main()
{
std::stack<int> newstack;
for(int J=0; J<10; J++)
[Link](J);
std::cout <<"Popping out elements?";
while (![Link] () )
{
std::cout <<" " << [Link]();

D
[Link]();
}

E
std::cout<<"\n";
return 0;

V
}

R
The output of the given C++ programme is as follows:
Popping out elements? 9 8 7 6 5 4 3 2 1 0

E
5.3 rePreSeNTINg STack USINg STaTIc arrayS
S
For representation of a stack using an array is one of the simplest methods to achieve the information.
E
But the major difference between an array and a stack is there. In array size is fixed whereas, the size
is not fixed in the stack, subsequently the size of stack is changed with the number of components
R
inserting or deleting from it. For achieving this a single dimensional array of specific size is declared
and the insertion and deletion of the elements are carried out using the LIFO mechanism, through a
pointer variable addressed as top, which is initialised with -1. For inserting an element on the stack, the
T

value of the top pointer is incremented by 1 and for deletion the respective top value is decreased by 1.
H

5.3.1 Stack Operations Making Use of arrays


IG

The following steps described below shows how the arrays could be used to implement stack for creation
of an empty stack is as follows:
1. Collectively put together all the header files required by the programme and initialise a constant
R

MAX with relevant value.


2. Declare all the methods or functions to be used in the programme.
Y

3. Create an array of a single dimension of fixed length (int stack [MAX]).


P

4. Declare an integer variable ‘top’, initialising it with '-1'.


O

5. In the main function, display a menu consisting of various operations related to stack and create
relevant function calls to perform the chosen operation.
C

The steps mentioned below are used for pushing an element on the stack is as follows:
1. Prove whether the stack is engaged or FULL. (Top == MAX-1).
2. If engaged, then display "Stack is completely engaged!!! Insertion is not possible!!!" and end the
function.
3. If it is empty, then increase the value of top by 1 (top++) and set stack [top] = value.

4
UNIT 05: Stacks JGI JAIN
DEEMED-TO-BE UNIVERSITY

The following steps help us to pop an element from the stack is as follows:
1. Verify whether stack is VACANT or EMPTY (top == -1).
2. If it is VACANT, then print "Stack is VACANT!!! We cannot delete!!!" and end the function.
3. If it is NOT VACANT, then remove the value at stack [top] and decrease top value by 1 (top--).

Lab exercise 5a: Write a Programme in c++ to implement stack operations.


The C++ programme that shows the implementation of operations of stack using array:
#include <iostream>

D
using namespace std;

E
#define SISE 5
int A[SISE];

V
int Top = -1;

R
bool isempty()
{

E
if(Top==-1)
return true;
else
return false;
S
E
}
R

void push(int value)


{
T

if(Top==SISE-1)
{ cout<<"Stack is full!\n";
H

}
else
IG

{
Top++;
A[Top]=value;
}
R

}
Y

void pop()
P

{
if(isempty())
O

cout<<"Stack is Empty!\n";
else
Top--;
C

void show_top()
{
if(isempty())
cout<<"Stack is Empty!\n";
else

5
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

cout<<"The element at top of the stack is: "<<A[Top]<<"\n";

void display_stack()
{
if(isempty())
{
cout<<"Stack is Empty!\n";
}

D
else
{

E
cout<<"The element of Stack is ";
for(int i=0 ; i<=Top; i++)

V
cout<<A[i]<<" ";
cout<<"\n";

R
}

E
}
S
E
int main()
{
R

int choice, flag=1, value;


while( flag == 1)
T

{
cout<<"Enter your choice (1-5)";
H

cout<<"\[Link] \[Link] \[Link] TOP ELEMENT \[Link] ELEMENT\


[Link]\n";
IG

cin>>choice; switch (choice)


{
case 1: cout<<"Enter the value of element: ";
R

cin>>value;
push(value);
Y

break;
case 2: pop();
P

break;
case 3: show_top();
O

break;
case 4: display_stack();
C

break;
case 5: flag = 0;
break;
}
}
return 0;
}

6
UNIT 05: Stacks JGI JAIN
DEEMED-TO-BE UNIVERSITY

The output of the given C++ programme is as follows:


Enter your choice (1-5)
[Link]
[Link]
[Link] TOP ELEMENT
[Link] ELEMENT
[Link]
1
Enter the value of element: 23

D
Enter your choice (1-5)
[Link]
[Link]

E
[Link] TOP ELEMENT

V
[Link] ELEMENT
[Link]

R
1
Enter the value of element: 34

E
Enter your choice (1-5)
[Link]
[Link]
[Link] TOP ELEMENT S
E
[Link] ELEMENT
[Link]
R
4
The element of Stack is 23 34
Enter your choice (1-5)
T

[Link]
H

[Link]
[Link] TOP ELEMENT
[Link] ELEMENT
IG

[Link]
2
Enter your choice (1-5)
R

[Link]
[Link]
Y

[Link] TOP ELEMENT


[Link] ELEMENT
P

[Link]
4
O

The element of Stack is 23


Enter your choice (1-5)
C

[Link]
[Link]
[Link] TOP ELEMENT
[Link] ELEMENT
[Link]

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

5.4 USINg dyNaMIc array fOr rePreSeNTINg STack


Dynamic stack resembles the dynamic array in many ways. It refers to the data structure whose capacity
fluctuates based on the real time operations like insertion or deletion of elements carried out in real
time environments. A stack implemented through array is known as static stack, to which we cannot
add elements exceeding its size, as the length of array remains fixed. To subdue this disadvantage to
subdue his disadvantage, we implement stack through linked list making it a dynamic stack.
The linked list contains subsequent links nodes, where node is made of two parts, the data and the
address. The data portion holds the actual value, whereas the address portion consists the address of

D
subsequence node. A pointer known as head holds the address of the initial node. The address portion of
the final node is made NULL, as it doesn't point to any node.

E
The data in the linked list is held in the nodes following the LIFO mechanism. We are aware that all the
operations could be done at one end of the stack alone. So while using linked list we consider the operable

V
end as either the head node or for the tail node of the linked list. The time complexity of carrying out the
operation at the final node is O(n) as we have to visit the entire linked list.

R
The following C++ programme depicts the implementation of stack using dynamic array:

E
#include <iostream>
#include <algorithm>
using namespace std; S
E
class myStack
{
R
sise_t capacity {0};
sise_t sise {0};
int *data {nullptr};
T

public:
void push(int n)
H

{
if (sise == capacity)
IG

{
cout << "Increase capacity by 5 elements" << endl;
capacity += 5;
R

int* tmp = new int[capacity];


copy_n(data, sise, tmp);
Y

swap(data, tmp);
delete[] tmp;
P

}
data[sise] = n;
O

++sise;
}
C

void print_all()
{
cout << "capacity=" << capacity << endl;
for (sise_t i = 0; i < sise; ++i)
cout << data[i] << " ";
cout << endl;
}
};

8
UNIT 05: Stacks JGI JAIN
DEEMED-TO-BE UNIVERSITY

int main(void) {
myStack S;
[Link](6);
[Link](7);
[Link](8);
[Link](9);
[Link](10);
S.print_all();
[Link](7);
S.print_all();

D
return 0;
}

E
The output of the given C++ programme is as follows:

V
Increase capacity by 5 elements
capacity=5

R
6 7 8 9 10
Increase capacity by 5 elements

E
capacity=10
6 7 8 9 10 7

5.5 aPPLIcaTIONS Of STack


S
E
In a stack, only restricted operations are accomplished because it is a classified data structure. The
R
components are removed since the stack in the reverse order. Some of the applications of stack are as
follows:
zz Expression evaluation
T

zz Expression conversion
H

zz Backtracking
Memory management
IG

zz

5.5.1 Polish and reverse Polish Notations


R

Notation could be described as a way to formulate the arithmetic expressions. We can express the
arithmetic equations using three distinguishable but analogous notations. Using any of these notations
Y

won’t alter the final result. The three equivalent notations are as follows:
Infix notation
P

zz

zz Prefix notation
O

zz Postfix notation
C

Infix Notation
In infix notation, e.g. a - b + c, where operators are used between operands. It is not possible for people
to read, write, and speak in infix notation but it does not go well by computing devices. An algorithm
to process infix notation might be challenging and expensive in terms of time and space consumption.
Consider an arithmetic expression x - y + z, where the mathematical symbols like +, - (operators) are
placed amidst of operands.

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Prefix Notation
In the prefix notation we will find that the expression containing the mathematical symbols or the
operands proceed or are prefixed to the variables (operands). For instance (+xy) which is similar to the
infix symbol (x+y). We can address this notation as a polish notation as well.

Postfix Notation
We address the postfix symbol as Reversed polish notation. Here the mathematical symbols (operators)
succeed the mathematical variables (operands).Say as an instance (xy+), which is similar to

D
corresponding infix expression(x+y).

E
5.5.2 Infix to Postfix conversion

V
For turning a given infix expression to the corresponding postfix string, the data structure stack is
utilised. We can obtain the mathematical symbols (operands) by examining the given infix string in

R
moving left to right manner. Upon the retrieval of an operand it is inserted in the postfix string. If
any princess or mathematical symbol (operator) is encountered then they are pushed onto the stack

E
maintaining the relevant precedence.

S
The following C++ programme transforms the infix notation to postfix notation:
#include <iostream>
E
#include <iterator>
R
#include <stack>
#include <sstream>
#include <vector>
T

using namespace std;


bool TryParse(const string &symbol);
H

int Priority(const string &c);


bool isOperator(const string &c);
IG

int main()
{
string infix = "9 + 8 + ( 5 - ( 4 * 3 ) ) / 4";// This is a infix
R

expression
istringstream iss(infix);
Y

vector<string> tokens;// Here we can store the tokens


while(iss)
P

{
string temperature;
O

iss >>temperature;
tokens.push_back(temperature);
C

}
vector<string> outputList;//output of vector
stack<string> s;//main stack
for(unsigned int i = 0; i < [Link](); i++) //read from right to
left
{
if(TryParse(tokens[i]))
{

10
UNIT 05: Stacks JGI JAIN
DEEMED-TO-BE UNIVERSITY

outputList.push_back(tokens[i]);
}
if(tokens[i] == "(")
{
[Link](tokens[i]);
}
if(tokens[i] == ")")
{
while(![Link]() && [Link]() != "(")

D
{
outputList.push_back([Link]());

E
[Link]();
}

V
[Link]();
}

R
if(isOperator(tokens[i]) == true)
{

E
while(![Link]() && Priority([Link]()) >= Priority(tokens[i]))
{
S
outputList.push_back([Link]());
[Link]();
E
}
R
[Link](tokens[i]);
}
}
T

while(![Link]())
{
H

outputList.push_back([Link]());
[Link]();
IG

for(unsigned int i = 0; i < [Link](); i++)


R

{
cout<<outputList[i];
Y

}
return 0;
P

}
bool TryParse(const string &symbol)
O

{
bool isNumber = false;
C

for(unsigned int i = 0; i < [Link](); i++)


{
if(!isdigit(symbol[i]))
{
isNumber = false;
}
else
{

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

isNumber = true;
}
}
return isNumber;
}
int Priority(const string &c)
{
if(c == "^")
{

D
return 3;
}

E
if(c == "*" || c == "/")
{

V
return 2;
}

R
if(c== "+" || c == "-")
{

E
return 1;
}
else
{
S
E
return 0;
R
}
}
bool isOperator(const string &c)
T

{
return (c == "+" || c == "-" || c == "*" || c == "/" || c == "^");
H

}
The output of the of the given C++ code is as follows:
IG

98+543*-4/+

5.5.3 Turning the Postfix expression to Infix expression


R

The following C++ programme transforms the postfix expression to infix expression:
Y

#include <bits/stdc++.h>
using namespace std;
P

bool isOperand(char x){


O

return((x>= 'A' && x <= 'Z') || (x >= 'A' && x <= 'Z'));
}
C

string postfixToInfix(string postfix_exp){


stack<string> S;
for(int i=0; postfix_exp[i]!='\0'; i++){
if(isOperand(postfix_exp[i])){
string op(1, postfix_exp[i]);
[Link](op);
}
else{

12
UNIT 05: Stacks JGI JAIN
DEEMED-TO-BE UNIVERSITY

string op1 = [Link]();


[Link]();
string op2 = [Link]();
[Link]();
[Link]("(" + op2 + postfix_exp[i] + op1 + ")");
}
}
return [Link]();
}

D
int main(){
string postfix_exp = "XYZ/-XK/W-*";

E
cout<<"Infix: "<<postfixToInfix(postfix_exp);
return 0;

V
}
The output of the given C++ programme is as follows:

R
Infix: ((X-(Y/Z))*((X/K)-W))

E
5.6 evaLUaTION Of POSTfIx exPreSSION

S
In the evaluation of a postfix expression, despite the fact that reading the expression from left to right,
the elements can be pushed in the stack if it is an operand.
E
And then POP the two operands from the stack, if it is an operator then estimate it. Push back the result
R
of the estimation. A guideline for evaluating postfix expression is as follows:
zz During the sinistrodextral scan of the postfix expression, the value is inserted into the stack if it is
found to be an operand.
T

zz Two consecutive operands are removed from stack, if the value is an operator, followed by computing
H

it.
zz The output of the estimated expression is inserted back into the stack. The entire process is rated
IG

until we reach the end of the postfix string. An example of evaluation of postfix string is shown in
Table1:
R

Table 1: evaluation of Insertion of Postfix String

Step Input Symbol Operation Stack calculation


Y

1. 4 Push 4
P

2. 5 Push 4,5
O

3. 6 Push 4,5,6
C

4. * Pop (2 elements) & evaluate 4 5*6=30

5. Push result (30) 4,30

6. + Pop (2 elements) & evaluate Empty 4+30=34

7. Push result (34) 34

13
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Step Input Symbol Operation Stack calculation


8. No more elements (pop) Empty 34 (result)

Following is the pseudo code for evaluating the postfix expression:


Postfix: Post expression
Stack: at first stack is empty
Token: stores scanned character for each iteration

D
Postfix: for i=1. LENGTH DO token: = postfix[i]
IF token is operand THEN

E
PUSH token to the stack
ELSE IF token is operator THEN

V
POP operands from stack.
NOW, perform the operation

R
PUSH the result to the stack
END

E
END FOR

S
Lab exercise 5b: Write a Programme in c++ to evaluate a Suffix expression using Stack.
E
The following C++ programme to evaluate value of a postfix expression:
#include <iostream>
R
#include <string.h>
using namespace std;
struct Stack
T

{
H

int Top;
unsigned Cap;
int* array;
IG

};

// Specifyign the operations of Stack


R

struct Stack* Create_Stack( unsigned Cap )


{
Y

struct Stack* stack = (struct Stack*) malloc(siseof(struct Stack));


P

if (!stack) return NULL;


O

stack->Top = -1;
stack->Cap = Cap;
C

stack->array = (int*) malloc(stack->Cap * siseof(int));

if (!stack->array) return NULL;

return stack;
}

int isEmpty(struct Stack* stack)

14
UNIT 05: Stacks JGI JAIN
DEEMED-TO-BE UNIVERSITY

{
return stack->Top == -1 ;
}

char peek(struct Stack* stack)


{
return stack->array[stack->Top];
}

char pop(struct Stack* stack)

D
{
if (!isEmpty(stack))

E
return stack->array[stack->Top--] ;
return '$';

V
}

R
void push(struct Stack* stack, char op)
{

E
stack->array[++stack->Top] = op;
}
S
// Specifying function to evaluate postfix expression
E
int Evaluate_Postfix(char* EXP)
{
R
// Create a stack equivalent to expression sise
struct Stack* stack = Create_Stack(strlen(EXP));
int i;
T

if (!stack) return -1;


H

// Checks all characters one by one


IG

for (i = 0; EXP[i]; ++i)


{
R

if (isdigit(EXP[i]))
push(stack, EXP[i] - '0');
Y

else
{
P

int Value1 = pop(stack);


int Value2 = pop(stack);
O

switch (EXP[i])
{
C

case '+': push(stack, Value2 + Value1); break;


case '-': push(stack, Value2 - Value1); break;
case '*': push(stack, Value2 * Value1); break;
case '/': push(stack, Value2/Value1); break;
}
}
}
return pop(stack);

15
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

// Specifying Main Function


int main()
{
char EXP[] = "456*+";
cout<<"The postfix evaluation of the expression is "<< Evaluate_
Postfix(EXP);
return 0;
}

D
The output of the given C++ programme is as follows:

E
The postfix evaluation of the expression is 34

V
5.7 TIMe cOMPLexITy aNaLySIS Of STackS

R
We can define the time complexity of an algorithm as a depiction of the time duration vital for the
underlying algorithm to accomplish its task. The function t(N) is used to indicate the relevant time

E
durations. N denotes the count of the steps required such that the individual steps are performed in a
specific time interval. For instance, We have O(1) as the time complexities for the insert() or Push() and
remove() or Pop() operations, since it involves single step.
S
E
Conclusion 5.8 cONcLUSION
R

zz A stack is an abstract structure containing a set of homogeneous components and is based on the
principle of Last In First Out (LIFO).
T

zz A stack has two simple services such as: PUSH, POP.


H

zz The PUSH operation is complete to insert an element into the stack.


zz The POP operation fetches the data element from the stack.
IG

zz The representation of a stack using an array is one of the simplest methods to achieve the information.
zz Dynamic stack resembles the dynamic array in many ways.
R

zz In the prefix notation we will find that the expression containing the mathematical symbols or the
operands proceeds.
Y

zz The postfix notation is addressed symbol as reversed polish notation.


P

5.9 gLOSSary
O

zz Stack: A data structure following the last in first out data manipulation process.
C

zz Push: It is used for inserting element at topmost position.


zz POP: The POP operation fetches the data element from the stack.
zz dynamic stack: It resembles the dynamic array in many ways.
zz Prefix notation: It will find that the expression containing the mathematical symbols or the
operands proceeds.
zz Postfix notation: It is addressed symbol as reversed polish notation.

16
UNIT 05: Stacks JGI JAIN
DEEMED-TO-BE UNIVERSITY

5.10 SeLf-aSSeSSMeNT QUeSTIONS

a. Multiple choice Questions


1. Which among the following is the postfix form of (P + Q)*(R*S – T)*U / V is?
a. PQ + RST * – * U *V /
b. PQ + RS* T – *U *V /

D
c. PQ + RS* T – U **V /
d. PQ + RS* T – UV/**

E
2. Which among the following is not an essential application of stack?

V
a. Retreating a string
b. Evaluation of postfix expression

R
c. Application of recursion

E
d. Job scheduling
3. Which data structure among the following is mostly used in a non recursive application of a recursive
algorithm? S
E
a. Tree
b. Queue
R

c. Stack
d. Linked list
T

4. Fetching the data reserved in a sequential access memory is alike to the process of data manipulation
H

on a __________.
a. Stack
IG

b. Array
c. Binary tree
R

d. Heap
5. Evaluate the postfix expression of P*Q+R/S is:
Y

a. P*QR+/S
P

b. PQ*RS/+
O

c. PQRS+/*
d. *PQ/RS+
C

6. Which of the following operation has the worst case linear time in the implementation of stack in
array?
a. PUSH
b. POP
c. Postfix
d. None of these

17
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

7. Which among the following type of expression in which operator make its operands to be succeed?
a. Prefix expression
b. Infix expression
c. Postfix expression
d. None of these
8. Number of stacks of size n essential to implement a queue of size n is:
a. Five

D
b. Two
c. One

E
d. Four

V
9. If the elements “W”, “X”, “Y” and “Z” are located in a stack and are removed one at a time, in what
order they will be removed?

R
a. WXYZ

E
b. ZYXW
c. ZYWX
d. WXZY S
E
10. Which among the following data structure is required to transform infix notation to postfix notation?
R
a. Heap sort b. Tree
c. Queue d. Stack
T

B. essay Type Questions


H

1. It is an abstract structure containing a set of homogeneous components and is based on the


principle of last in first out (LIFO). What is a Stack?
IG

2. A stack has two simple services such as: PUSH, POP. Describe the operations of stacks.
3. A stack using an array is one of the simplest methods to achieve the information. Explain the
representation of stack using static arrays.
R

4. In the evaluation of a postfix expression, despite the fact that reading the expression from left to
Y

right, the elements can be pushed in the stack if it is an operand. Define the significance of evaluation
of postfix expression.
P

5. In a stack, only restricted operations are accomplished because it is a classified data structure.
O

Determine the applications of stack.


C

5.11 aNSWerS aNd HINTS fOr SeLf-aSSeSSMeNT QUeSTIONS

a. answers to Multiple choice Questions

Q. No. answer
1. d. PQ + RS* T – UV/**

18
UNIT 05: Stacks JGI JAIN
DEEMED-TO-BE UNIVERSITY

Q. No. answer
2. d. Job scheduling

3. c. Stack

4. a. Stack

5. b. PQ*RS/+

6. d. None of these

D
7. c. Postfix expression

E
8. b. Two

9. b. ZYXW

V
10. d. Stack

R
B. Hints for essay Type Questions

E
1. A stack is an abstract structure containing of a set of homogeneous components and is based on the
S
principle of last in first out (LIFO). It is a usually used abstract data type with two major operations,
namely push and pop. Push and pop are carried out on the topmost element, which is the item best
E
recently added to the stack.
R
Refer to Section Introduction
2. A stack has two simple services such as: PUSH, POP. The PUSH methods adds an element at the top
of the stack whereas, the POP method eliminates the element from the top of the stack. The PEEK
T

method returns the value to the topmost element of the stack.


H

Refer to Section Operations of Stack


3. For representation of a stack using an array is one of the simplest methods to achieve the information.
IG

But the major difference between an array and a stack is there. In array size is fixed whereas, the size
is not fixed in the stack, subsequently the size of stack is changed with the number of components
inserting or deleting from it.
R

Refer to Section Representing Stack Using Static Arrays


4. In the evaluation of a postfix expression, despite the fact that reading the expression from left to
Y

right, the elements can be pushed in the stack if it is an operand. And then POP the two operands
P

from the stack, if it is an operator then estimate it.


Refer to Section Evaluation of Postfix Expression
O

5. In a stack, only restricted operations are accomplished because it is a classified data structure. The
components are removed since the stack in the reverse order.
C

Refer to Section Applications of Stack

@ 5.12 POST-UNIT readINg MaTerIaL

zz [Link]
zz [Link]

19
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

5.13 TOPIcS fOr dIScUSSION fOrUMS

zz Discuss with your friends and classmates about the concept of stacks and its operations. Also,
discuss about the applications of stack and dynamic array for representing stack.

D
E
V
R
E
S
E
R
T
H
IG
R
Y
P
O
C

20
UNIT

06

D
E
Queue

V
R
E
Names of Sub-Units S
E
Introduction to Queue, Array Representation of Queue, Queue Operations, Queue Types, Application of
R
Queues, Time and Space Complexity Analysis of Queues.
T

Overview
H

This unit begins by discussing about the concept of queue. Next, the unit discusses the array
representation of queue. Further the unit explains the operations of queue, types of queue and
IG

application of queue. Towards the end, the unit discusses the time and space complexity analysis of
queues.
R

Learning Objectives
Y

In this unit, you will learn to:


P

a Discuss the concept of queue


O

a Explain the concept of array representation of queue


a Describe the types and application of queue
C

a Explain the significance of queue operations


a Discuss the time and space complexity analysis of queue
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit you would:


a Evaluate the concept of queue
a Assess the concept of array representation of queue
a Evaluate the importance of operations of queue
Determine the types and application of queue

D
a

a Explore the time and space complexity analysis of queue

E
V
Pre-Unit Preparatory Material

R
a [Link]

E
6.1 INTrOdUcTION
S
We can refer Queue as an ADT (Abstract Data Type), which resembles stacks. The elements of the queue
E
are accessible from either its extremes or endpoints. One of the extreme is meant for insertion and
another acts as an endpoint for deletion.
R

The method of inserting data from an endpoint of the queue is called Enqueuers, while the method of
removing the data elements from the queue is called Dequeuers. The queue uses the FIFO (First in First
T

out) mechanism for the insertion or removal of the data elements.


H

For example, One of the concrete example of the queue, is, a solitary alley uni-directional highway, where
an automobile going initially, leaves earlier. Further examples include the long lines of passenger at the
ticket counters.
IG

6.2 defINITION Of QUeUe


R

We can define queue to be a linear data structure which follows a specific mechanism for enacting the
tasks or operations. The queue uses FIFO (First in First out) mechanism for data handling. For instance,
Y

a line of customers waiting for supplies are served in their order of arrival.
The distinguishing factor between stack and queue lies in the process of data removal. The most newly
P

inserted data item is removed from the stack whereas in queue we delete the data item which was
O

inserted most earlier.


C

6.3 ArrAy rePreSeNTATION Of QUeUe


The linear arrays can be utilised to denote queues. The variables front and rear are commonly
encountered in all the operations of queue. They indicate the location where we perform the addition
and removal of the data elements.
In the beginning, the front and rear are set to -1 which indicates a vacant queue.

2
UNIT 06: Queue JGI JAIN
DEEMED-TO-BE UNIVERSITY

Figure 1 depicts a queue consisting 5 data values, beside the corresponding values of front and rear, in
its array representation:

H E L L O

0 1 2 3 4 5

front rear

D
0 4

Queue

E
figure 1: Queue representation

V
6.3.1 Queue representation through Arrays

R
Queue can be represented by using arrays as it is a linear data structure. The Figure 1 shown above,
displays a row of English alphabets denoting the word “HELLO” as the q has not undergone any data

E
removal till now, Front variable retains -1. But the variable Rear gets incremented by one each time

S
during the data insertion process. After the insertion process the queue resembles the figure below.
The variable rear gets incremented till 5, where the variable Front retains the identical value. Figure 2
E
represent queue through array:
R

H E L L O G
0 1 2 3 4 5
T
H

front rear
IG

0 5

Queue after inserting an element


R

figure 2: represent Queue through Array


Y

The variable Front is incremented to 0 from -1 after the removal of data in the queue. After the deletion,
the queue will hold the data elements as shown Figure 3:
P
O

E L L O G

0 1 2 3 4 5
C

front rear
1 5

figure 3: Queue after deleting an element

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

6.3.2 Algorithm depicting data Insertion in the Queue


The following points represents the data insertion in queue:
Step 1: Whether REAR = MAX – 1, IF Yes
Display DATA OVERFLOW
Proceed to step 4
[END IF]

D
Step 2: Whether FRONT = -1 and REAR = -1, IF yes,
Put FRONT = REAR = 0

E
Put REAR = REAR + 1

V
[END IF]

R
Step 3: Put QUEUE [REAR] = VALUE

E
Step 4: STOP

6.3.3 Algorithm for deletion Process in Queue S


E
The following points represents the data deletion in queue:
R
Step 1: Whether FRONT = -1 or FRONT > REAR IF yes
Display DATA UNDERFLOW
T

ELSE
H

PUT VAL = QUEUE[FRONT]


IG

PUT FRONT = FRONT + 1


[END IF]
R

Step 2: STOP
Y

6.3.4 Insertion and deletion in Queue in c++


P

Lab exercise 6a: Write a Programme in C++ to implement Queue Operations.


The following C++ Programme shows the insertion and deletion in queue in C++:
O

#include <iostream>
#include <cstdlib>
C

using namespace std;


#define SISE 7
class queue
{
int *arr;
int Capacity;
int Front;

4
UNIT 06: Queue JGI JAIN
DEEMED-TO-BE UNIVERSITY

int Rear;
int count;

public:
queue(int sise = SISE); // constructor
~queue(); // destructor

void dequeue();
void enqueue(int x);
int peek();

D
int sise();
bool isEmpty();

E
bool isFull();
};

V
queue::queue(int sise)
{

R
arr = new int[sise];
Capacity = sise;

E
Front = 7;
Rear = -1;
count = 0; S
E
}
queue::~queue() {
R
delete[] arr;
}
void queue::dequeue()
T

{
if (isEmpty())
H

{
cout << “Underflow\nProgramme Terminated\n”;
IG

exit(EXIT_FAILURE);
}
cout << “Removing element from queue “ << arr[Front] << endl;
R

Front = (Front + 1) % Capacity;


count--;
Y

}
void queue::enqueue(int item)
P

{
if (isFull())
O

{
cout << “Overflow\nProgramme Terminated\n”;
C

exit(EXIT_FAILURE);
}

cout << “Inserting “ << item << endl;


Rear = (Rear + 1) % Capacity;
arr[Rear] = item;
count++;

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

}
int queue::peek()
{
if (isEmpty())
{
cout << “Underflow\nProgramme Terminated\n”;
exit(EXIT_FAILURE);
}
return arr[Front];
}

D
int queue::sise() {
return count;

E
}
bool queue::isEmpty() {

V
return (sise() == 0);
}

R
bool queue::isFull() {
return (sise() == Capacity);

E
}
int main()
{ S
E
// create a queue of capacity 7
queue q(7);
R
[Link](3);
[Link](4);
[Link](5);
T

cout << “The front element in queue is “ << [Link]() << endl;
[Link]();
H

[Link](4);
cout << “Sise of the queue is” << [Link]() << endl;
IG

[Link]();
[Link]();
[Link]();
R

if ([Link]()) {
Y

cout << “The queue is vacant\n”;


}
P

else {
cout << “The queue is not empty\n”;
O

}
C

return 0;
}
The output of the above C++ programme is as follows:
Inserting 3
Inserting 4
Inserting 5
The front element in queue is 0

6
UNIT 06: Queue JGI JAIN
DEEMED-TO-BE UNIVERSITY

Removing element from queue 0


Inserting 4
Sise of the queue is3
Removing element from queue 4
Removing element from queue 5
Removing element from queue 4
The queue is vacant

6.4 OPerATIONS IN QUeUe

D
A queue is an object that permits the following operations are as follows:
zz enqueuer(x): Inserting a data element A at the rear end of queue.

E
zz dequeuer (): A data element is deleted from the front end of queue.

V
zz empty (): Verifies whether a queue is vacant or occupied.

R
6.4.1 Technique in Queue

E
To achieve the reversal of queue, we utilise the data structure stack which follows the LIFO mechanism.
Following this approach, the last data value added to stack will be the initial data value of the reversed
S
queue. The following points show the LIFO mechanisms are as follows:
Add the data items to the stack after removing them from the queue. The uppermost value of the
E
zz
stack becomes the final value of the queue.
R
zz Add the data items to the queue after removing them from the stack. The final data value of the
stack becomes the initial data value to be pushed onto the queue.
T

6.4.2 reversal of Queue using recursion


H

The following programme shows the reversal of queue using recursion in C++ is as follows:
#include <bits/stdc++.h>
IG

using namespace std;


// A function to print the queue
void printQueue(queue<long long int> Queue)
R

{
while (![Link]()) {
Y

cout << [Link]() << “ “;


[Link]();
P

}
}
O

// Reverse the queue using recursive functions


void reverseQueue(queue<long long int>& q)
C

{
// Base case
if ([Link]())
return;
// from the fornd end dequeue the current item
long long int data = [Link]();

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

[Link]();
// remaining queue should be reversed
// Enqueue current item (to rear)
[Link](data);
}
// Drive code
int main()
{
queue<long long int> queue;

D
[Link](65);
[Link](72);

E
[Link](35);
[Link](40);

V
[Link](95);
[Link](29);

R
[Link](85);
[Link](65);

E
[Link](56);
[Link](100);
reverseQueue(queue);
printQueue(queue);
S
E
}
R
The output of the above C++ programme is as follows:
72 35 40 95 29 85 65 56 100 65
T

6.4.3 Analysis of Involved complexities in Queue


H

The following points shows the complexities in queue are as follows:


IG

zz Time complexity: The time complexity of the above queue reversal process is O(n). Since we have to
add all the data items initially in the stack followed by inserting in queue.
zz Auxiliary Space: The space complexity of the occupied space required for the above Universal
R

process is O(N). Since we use stack to hold data items.


Y

6.5 TyPeS Of QUeUeS


P

There are three types of queues are as follows:


Circular queue
O

zz

zz Priority queue
C

zz Dequeue

6.5.1 circular Queue


We can define a Circular queue as a linear data structure, where the final location is attached to the
initial location forming a circle, and various related operations make use of the FIFO (First in First out
mechanism).

8
UNIT 06: Queue JGI JAIN
DEEMED-TO-BE UNIVERSITY

It is popular as Ring Buffer. An example of circular queue is shown in Figure 4:

Front
7 0

10

1
6

20

D
30
5

E
2
50 40

V
4 3

R
Rear

E
figure 4: circular Queue

6.5.2 circular Queues Using dynamic Arrays S


E
If we produce a queue by means of an array, where enqueuing and dequeuing receipts O(1) time and
space complexity each, one of the queue is occupied, you cannot add new elements, similarly sometimes
R
when you remove elements, the queue can be totally vacant, but still the front will be in the back utmost
position, so you can’t add any value over there.
T

Lab exercise 6b: Write a Programme in C++ to implement Circular Queue Operations.
H

The following C++ programme shows the implementation of a circular queue using dynamic arrays is
as follows:
IG

#include <iostream>
using namespace std;
int circularqueue[5];
R

int front = -1, rear = -1, n=5;


void insertCQ(int val) {
Y

if ((front == 0 && rear == n-1) || (front == rear+1)) {


cout<<”Queue is overflow \n”;
P

return;
}
O

if (front == -1) {
front = 0;
C

rear = 0;
} else {
if (rear == n - 1)
rear = 0;
else
rear = rear + 1;
}
circularqueue[rear] = val ;

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

}
void deleteCQ() {
if (front == -1) {
cout<<”Queue Underflow\n”;
return ;
}
cout<<”Element deleted from queue is: “
<<circularqueue[front];
if (front == rear) {
front = -1;

D
rear = -1;
} else {

E
if (front == n - 1)
front = 0;

V
else
front = front + 1;

R
}
}

E
void displayCQ() {
int f = front, r = rear;
if (front == -1) { S
E
cout<<”Queue is empty”<<endl;
return;
R
}
cout<<”The element in Queue are :\n”;
if (f <= r) {
T

while (f <= r){


cout<<circularqueue[f]<<” “;
H

f++;
}
IG

} else {
while (f <= n - 1) {
cout<<circularqueue[f]<<” “;
R

f++;
}
Y

f = 0;
while (f <= r) {
P

cout<<circularqueue[f]<<” “;
f++;
O

}
}
C

cout<<endl;
}
int main() {
int ch, val;
cout<<”1)Insert\n”;
cout<<”2)Delete\n”;
cout<<”3)Display\n”;

10
UNIT 06: Queue JGI JAIN
DEEMED-TO-BE UNIVERSITY

cout<<”4)Exit\n”;
do {
cout<<”Select the desired element”;
cin>>ch;
switch(ch) {
case 1:
cout<<”Input for insertion”;
cin>>val;
insertCQ(val);
break;

D
case 2:
deleteCQ();

E
break;
case 3:

V
displayCQ();
break;

R
case 4:
cout<<”Exit\n”;

E
break;
default: cout<<”Invalid!\n”;
} S
E
} while(ch != 4);
return 0;
R
}
The output of the given C++ programme is as follows:
T

1)Insert
2)Delete
H

3)Display
4)Exit
IG

Select the desired element 1


1
Input for insertion 34
34
R

Select the desired element 1


1
Y

Input for insertion 56


56
P

Select the desired element 3


O

3
The element in Queue are:
34 56
C

Select the desired element 2


2
Element deleted from queue is: 34
Select the desired element 4
4
Exit

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

6.5.3 dequeues
The dequeue stands for Double Ended Queue. The data addition in normal queue occurs at one thrilling
called as rear end, and the elimination of data occurs at the other extreme known as front end. An
example of dequeue is shown in Figure 5:

D
0 1 2 3 4

E
figure 5: dequeue
In the Double ended queue the data addition and removal processes are carried out at both the extremes.

V
Following are some of the properties of queue are as follows:

R
zz Dequeue can act either as a stack or a queue, since the data addition and removal processes are
carried out at both the extremes.

E
zz In the Double ended queue, the data addition and removal processes can be carried out at one end

S
which makes it act like a stack. In such case, the queue follows LIFO principle. Figure 6 shows the
data addition and removal process:
E
R

0 1 2 3 4
T
H

figure 6: data Addition and removal Process


zz A Double ended queue can act like a Queue, If the data addition is carried out at one extreme and the
data removal is carried out at the other extreme. In such cases the queue works on FIFO mechanism.
IG

Figure 7 shows the addition and deletion of queue in different extreme:


R

0 1 2 3 4
Y

figure 7: Addition and deletion of Queue in different extreme


P

Queues can be divided into two categories are as follows:


O

zz Input-restricted queue: In such a queue constraints are exerted during the data addition process.
Here the data is added to the queue from one end but the removal can happen from both extremes.
C

Figure 8 shows the data addition from one end and removal of data from both extremes:

0 1 2 3 4

figure 8: data Addition from One end and removal of data from Both extremes

12
UNIT 06: Queue JGI JAIN DEEMED-TO-BE UNIVERSITY

zz Output-restricted queue: In such a queue constraint is exerted during the data removal process.
Here the data removal happens from one end, whereas the data insertion can happen from both the
extremes. Figure 9 shows the data deletion from one end and insert from both the extremes:

0 1 2 3 4

D
figure 9: data is removed from One end and Insert from Both the extremes

E
The following operations are implemented on dequeuer are as follows:

V
zz Insertion of data from front end

R
zz Deletion of data from end
zz Insertion of data at the rear

E
zz Deletion of data from the rear end

S
Apart from the above, peek operation can also be performed on dequeue. The peek operation retains the
data elements present at the front and the rear ends.
E
Additional operations of dequeuer are as follows:
R

zz isfull (): if the stack is fully occupied the function retains true, else, it retains false.
zz isempty (): if the stack is vacant the function retains true else it retains false.
T
H

6.5.4 Priority Queues


A priority queue refers to a specialised queue where each data element has a predetermined service
IG

priority. Here, the elements are enqueued at the extreme called rear in the arrival order of the data
elements ,Whereas the data elements are dequeued at the front end based on the preferences or the
priority of the data elements. An element with lower preference will be dequeued later than the element
R

with higher preference. Figure 10 shows the priority queue:


Y

Low Priority High Priority


P
O
C

Rear Front
(Enqueue) (Dequeue)

figure 10: Priority Queues


If multiple items have identical priorities, then they are removed according to their arrival order. This
mechanism has its application in dealing with interrupts, in Prim’s algorithm, in Dijkstra’s algorithm, A
search algorithm, heap sort, and Huffman code generation.

13
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

6.6 A MAzINg PrOBLeM


A group of blocks are organised in a stable in an N*N matrix holding a binary values is mentioned as
Maze, where, the uppermost block existing at the left extreme that is maze[0][0],acts as source and the
lower block existing at the right extreme that is maze[N-1][N-1], acts as the endpoint. The two directions
downward and forward are the only pathways for the rat’s movement. In the matrix of the Maze,
presence of zero signifies that the block is a blind alley and presence of 1 implies the block could act as a
pathway to destination from the respective source. And intricate form of the above maze problem, could
be, that, the four directions are open for the rat’s movement but with restricted moves.

D
In the maze, the letters denote either a point for making decisions or a point acting as dead end. In
order to be aware of what the letter indicates we have to inspect the point. The Exit point is denoted by
the letter X. After reaching to a point denoted with letter, insert the neighbouring points denoted with

E
letters to the queue including the initial point.(leave the previously inspected points). Following rules are
applicable for resolving the maze problems are as follows:

V
zz After reaching to a point denoted with letter, insert the neighbouring points denoted with letters to

R
the queue including the initial point. (Leave the previously inspected points).
zz To decide upon the visit to the next position, a point from the queue is deleted, and a movement is

E
made to the respective point.
An example of a mazing problem is shown in Figure 11.
S
Blue coloured blocks represent the blind alley or dead ends (Matrix held value = 0).
E
R
Source
T
H
IG

Dest.
R

figure 11: Sample of Maze


The maze below indicates the resolved marked pathway is shown in Figure 12:
Y
P

Source
O
C

Dest.

figure 12: resolved Marked Pathway of Blind Alley and dead end
Connecting all the 1s together in the above matrix forms the resolved pathway.

14
UNIT 06: Queue JGI JAIN
DEEMED-TO-BE UNIVERSITY

6.7 IMPLeMeNTINg MULTIPLe STAckS ANd QUeUeS


The working mechanism of the stack Last in First out (LIFO) needs to be considered during the
implementation of queue through stacks.
For the Enqueue operation a single stack is needed, whereas for Dequeue operation two stacks are
required.
The following programme shows the implementation of multiple stacks and queues are as follows:
#include <iostream>

D
using namespace std;
int stack[100], n = 100, Top = -1;
void push(int val) {

E
if(Top >= n-1)

V
cout<<”Stack Overflow”<<endl;
else {

R
Top++;
stack[Top] = val;

E
}
}
void pop() {
if(Top <= -1) S
E
cout<<”Stack Underflow”<<endl;
else {
R
cout<<”The popped elements are “<< stack[Top] <<endl;
Top--;
}
T

}
H

void display() {
if(Top>= 0) {
cout<<”Elements in the stack are :”;
IG

for(int i = Top; i>= 0; i--)


cout<<stack[i]<<” “;
cout<<endl;
R

} else
cout<<”Stack is vacant”;
Y

}
int main() {
P

int ch, val;


cout<<”1) Push in stack”<<endl;
O

cout<<”2) Pop from stack”<<endl;


cout<<”3) Display stack”<<endl;
C

cout<<”4) Exit”<<endl;
do {
cout<<”Enter the desired element: “<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<”Enter value to be pushed:”<<endl;
cin>>val;

15
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;

D
}
case 4: {

E
cout<<”Exit”<<endl;
break;

V
}
default: {

R
cout<<”Invalid desired”<<endl;
}

E
}
}while(ch = 4);
return 0; S
E
The output of the given C++ programme is as follows:
1) Push in stack
R

2) Pop from stack


3) Display stack
T

4) Exit
Enter the desired element:
H

1
Enter value to be pushed:
IG

12
Enter the desired element:
1
Enter value to be pushed:
R

14
Enter the desired element:
Y

1
Enter value to be pushed:
P

16
O

Enter the desired element:


1
Enter value to be pushed:
C

18
Enter the desired element:
3
Elements in the stack are: 18 16 14 12
Enter the desired element:
2
The popped elements are 18

16
UNIT 06: Queue JGI JAIN
DEEMED-TO-BE UNIVERSITY

Enter the desired element:


4
Exit
Enter the desired element:
}
Time Complexity for execution of above C++ programme is as follows: For performing these operations
through stack the execution time in the worst case is O(n) since we require to move the n data items from
stack 1 to stack 2,upon calling the Dequeue operation. The time complexity for inserting data element
to stack 1 is O(1).

D
6.8 TIMe cOMPLexITy ANALySIS Of QUeUeS

E
We remain aware of the locations of the data insertion and removal while dealing with Queues.
Therefore, these dual operations could be achieved in one step. Following are the time complexity of

V
queues analysis is as follows:

R
zz The time complexity for operation Enqueue: O(1)
zz The time complexity for operation Dequeue: O(1)

E
zz The time complexity for calculating the Size: O(1)

6.9 cONcLUSION
S
E
Conclusion

Queue as an ADT (Abstract data type), which resembles stacks.


R
zz

zz Queue can be represented by using arrays as it is a linear data structure.


zz To achieve the reversal of queue, we utilise the data structure stack which follows the LIFO mechanism.
T

zz The time complexity of the above queue reversal process is O(n).


H

zz The space complexity of the occupied space by the queue is O(N).


The dequeue stands for Double Ended Queue.
IG

zz

zz A Priority Queue refers to a specialised queue where each data element has a predetermined service
priority.
R

6.10 gLOSSAry
Y

zz Queue: A data structure with organises list of data values.


P

zz dequeue: In the Double ended queue the data addition and removal processes are carried out at
O

both the extremes.


zz data: It refers to the information.
C

zz Priority queue: It refers to a specialised queue where each data element has a predetermined service
priority.
zz enqueuer(x): Inserting a data element A at the rear end of queue.
zz empty (): It verifies whether a queue is vacant or occupied.
zz circular queue: It defines a Circular queue as a linear data structure, where the final location is
attached to the initial location.
zz Time complexity: The time complexity of the reversal of queue is O(n).

17
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

6.11 SeLf-ASSeSSMeNT QUeSTIONS

A. Multiple choice Questions


1. Which among the following specifies the sustainable application of the data structure Queue?
a. While multiple customers share and like resource.
b. If there is an asynchronous data allocation among processes.

D
c. Distributing and balancing of data or web traffic load.
d. All of these

E
2. There are __________ number of stacks required for implementing a queue, when no alternative
data structures like arrays are linked lists are present.

V
a. 13 b. 2

R
c. 15 d. 6
3. There are __________ number of queues required to implement a stack, when no alternative data

E
structures like Arrays and Linked list are present.
a. 10
c. 12
b.
d.
S
2
8
E
4. Choose the efficient data structure for implementing priority queues:
R

a. Dynamic array
b. Linked List
T

c. Binary heap
H

d. None of these
5. Choose the correct statement regarding the implementation of queue through linked list.
IG

a. During the data insertion, if we add new nodes at the starting of linked list, then in the data
removal process, we must delete nodes from end of the linked list.
b. If we add new nodes at the end of the linked list during the data insertion process, then we must
R

delete the nodes in the data removal operation.


Y

c. Both a and b
d. None of these
P

6. How many numbers of stacks are required to implement the queue?


O

a. 5 b. 3
c. 2 d. 1
C

7. Which of the following data structure is needed for breadth first traversal on a graph?
a. Dynamic array b. Binary search tree
c. Stack d. Queue
8. Which among the following is correct about the context of queue?
a. First in First Out list b. Last in First Out list
c. Linked List d. All of these

18
UNIT 06: Queue JGI JAIN
DEEMED-TO-BE UNIVERSITY

9. Where does a new element is imparted in the implementation of queue in a linked list?
a. At the top of the linked list
b. At the bottom of the linked list
c. At the tail of the linked list
d. None of these
10. Determine the data structure in which elements can be inserted or removed from both the ends but
not from the middle is:

D
a. Array b. Enqueuer
c. Circular queue d. All of these

E
B. essay Type Questions

V
1. It is a linear data structure which follows a specific mechanism for enacting the tasks or operations.
What is a Queue?

R
2. The linear arrays can be utilised to denote queues. The variables front and rear are commonly

E
encountered in all the operations of queue. Describe the representation of queue in array.
3. Simple queue describes the simple operation of queue in which insertion arises at the rear of the list
S
and deletion arises at the front of the list. Explain the types of queue.
E
4. It refers to a specialised queue where each data element has a predetermined service priority. Here,
the elements are enqueued at the extreme called Rear, in the arrival order of the data elements.
R
Describe the priority queue.
5. We remain aware of the locations of the data insertion and removal while dealing with Queues.
Determine the time complexity analysis of queue.
T
H

6.12 ANSwerS ANd HINTS fOr SeLf-ASSeSSMeNT QUeSTIONS


IG

A. Answer to Multiple choice Questions


R

Q. No. Answer
1. c. Distributing and balancing of data or web traffic load.
Y

2. b. 2
P

3. b. 2
O

4. c. Binary heap
5. c. Both a and b
C

6. c. 2
7. c. Stack
8. a. First in First Out list
9. c. At the tail of the linked list
10. c. Circular queue

19
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

B. Hints for essay Type Questions


1. A queue to be a linear data structure which follows a specific mechanism for enacting the tasks or
operations. The queue uses FIFO (First in First out) mechanism for data handling. For instance, a
line of customers waiting for supplies are served in their order of arrival. The distinguishing factor
among stack and queue lies in the process of data removal.
Refer to Section Definition of Queue
2. The linear arrays can be utilised to denote queues. The variables front and rear are commonly
encountered in all the operations of queue. They indicate the location where we perform the addition

D
and removal of the data elements. In the beginning, the front and rear are set to -1 which indicates
a vacant queue.

E
Refer to Section Array Representation of Queue
3. There are four types of queues are as follows:

V
z Simple queue

R
z Circular queue

E
z Priority queue
z Dequeue
Refer to Section Types of Queue S
E
4. A priority queue refers to a specialised queue where each data element has a predetermined service
priority .Here, the elements are enqueued at the extreme called rear, in the arrival order of the data
R

elements, Whereas the data elements are dequeued at the front end based on the preferences or the
priority of the data elements.
T

Refer to Section Types of Queue


5. We remain aware of the locations of the data insertion and removal while dealing with Queues.
H

Therefore these dual operations could be achieved in one step.


IG

Refer to Section Time Complexity Analysis of Queue

@ 6.13 POST-UNIT reAdINg MATerIAL


R

zz [Link]
Y

zz [Link]
P
O

6.14 TOPIcS fOr dIScUSSION fOrUMS

Discuss with your friends and classmates about the concept of queue and its representation in
C

zz
array. Also, discuss the types of queue, its application and work with the relevant programmes and
understand its working mechanism.

20
UNIT

07

D
E
Linked List

V
R
E
Names of Sub-Units
S
E
Introduction to Linked List, Representation of Linked Lists in Memory, Memory Allocation, Linked List
R
Operations, Types of Linked List, Linked Stacks and Queues, Applications of Linked List
T

Overview
H

This unit begins by discussing the concept of linked list. Next, the unit explains the representation of
linked lists in memory, memory allocation and linked list operations. Further, the unit explains the
IG

types of linked list, linked stacks and queues. Towards the end, the unit discusses the applications of
linked list.
R

Learning Objectives
Y

In this unit, you will learn to:


P

a Discuss the concept of linked list


O

a Explain the concept of representation of linked lists in memory, memory allocation and linked list
operations
C

a Describe the types of linked list


a Explain the significance of linked stacks and queues
a Discuss the applications of linked list
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of linked list
a Assess the concept of representation of linked lists in memory, memory allocation and linked list
operations
a Evaluate the importance of types of linked list

D
a Determine the significance of linked stacks and queues
a Explore the applications of linked list

E
V
Pre-Unit Preparatory Material

R
a [Link]

E
7.1 INTrOdUcTION
S
In a data structure, linked list is generally a chain of nodes in which each node is connected to each other
E
by means of pointers or references. The size of a linked list can vary depending on the requirements of
the users, hence it is dynamic in nature. Linked list considered as a collection or sequence of the same
R
kind of items. It is the second most-used data structure after the array. The building block of linked list
is known as node.
T

7.2 rePreSeNTaTION Of LINked LIST IN MeMOry


H

A list is an ordered datatype in which the elements are kept in a sequence efficiently for the retrieval
of elements. It allows the recurrence that means a particular part of a data can be occur more than
IG

one time in a list. When the similar kind of data is entered numerous times in list, each entry of that
recurring data is considered as a discrete item.
An array or list is very much similar but the main difference between the array and the list is that array
R

stores homogenous data whereas the list stores heterogeneous data items. Linked list is also considered
as sequence in data structure. The representation of linked list is shown in Figure 1:
Y

Head
P
O

A B C D Null
C

Data Next

figure 1: representation of Linked List

7.3 MeMOry aLLOcaTION


Memory allocation is the process of storing and preserving a comprehensive and uncomprehensive
part of computer memory for the implementation of programs and procedures. It is concluded through

2
UNIT 07: Linked List JGI JAIN
DEEMED-TO-BE UNIVERSITY

a process is called memory management. Before the implementation of any process it must be first
located in the memory. The space or area where process is placed is allocated by a memory.
The memory allocation is further classified into two categories:
zz Static memory allocation
zz Dynamic memory allocation

7.3.1 Static Memory allocation

D
Static memory allocation is achieved during compilation. The node of block and memory stored will
be freed during time of compiling. When there is more than required memory it will be wastage. When
the memory is not as much of as the required memory, the program is not able to run further. The

E
requirement of memory should be known in advance.

V
The following C++ program is used to show the implementation of static memory allocation using array
are as follows:

R
// C++ program to illustrate
// non-static data members

E
using namespace std;
#include <iostream>
class GfG { S
E
private:
// Creation of static variable
R
static int count;
public:
void set_count()
T

{
count++;
H

}
// Funciton to access the private members
IG

void show_count()
{
// Display count variable
R

cout << count << '\n';


}
Y

};
int GfG::count = 0;
P

int main()
{
O

// class GfG objects


GfG A1, A2, A3, A4, A5;
C

A1.set_count();
A2.set_count();
A3.set_count();
A4.set_count();
A5.set_count();
// Display count function
A1.show_count();
A2.show_count();

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

A3.show_count();
A4.set_count();
A5.set_count();
return 0;
}
The output of given C++ code is as follows:
/tmp/0U3BJxRuLJ.o
5
5

D
5

E
7.3.2 dynamic Memory allocation
Dynamic memory allocation is just opposite to the static memory, in which the requirement of memory

V
is describe during the implementation of program. In dynamic memory, we can allocate the memory
acc to our requirement as there is not wastage of memory. Hence, it is not essential to know the exact

R
memory requirement previously. The following C++ program is used to show the implementation of
dynamic memory allocation using array are as follows:

E
#include <iostream>
using namespace std;
int main () S
E
{
// Initialization of pointer to NULL
R
int* N = NULL;
N = new(nothrow) int;
if (!N)
T

cout<< "allocation of memory failed\n";


H

else
{
IG

// Values should be stored in allocated address


*N=59;
cout<<"The value of N: " << *N <<endl;
}
R

float *L = new float(85.30);


cout<< "The value of L: " << *L <<endl;
Y

// Size of memory for block


int size = 9;
P

int *arr = new(nothrow) int[size];


O

if (!arr)
cout<< "allocation of memory failed\n";
else
C

{
for (int i = 0; i< size; i++)
arr[i] = i+1;
cout<< "The value stored in block of memory: ";
for (int i = 0; i< size; i++)
cout<<arr[i] << " ";
}
delete N;

4
UNIT 07: Linked List JGI JAIN
DEEMED-TO-BE UNIVERSITY

delete L;
// freed the block of allocated memory
delete[] arr;
return 0;
}
The output of given C++ code is as follows:
/tmp/0U3BJxRuLJ.o
The value of N: 59
The value of L: 85.3

D
The value stored in block of memory: 1 2 3 4 5 6 7 8 9

E
7.4 LINked LIST OPeraTIONS
In data structure, there are linked list operations which allow us to perform distinct action on linked list.

V
Some of the linked list operations are as follows:

R
zz Traversing
zz Searching

E
zz Insertion
zz Deletion
S
E
7.4.1 Traversing
R
A linked list is a linear data structure that involve traverse of node in every state of singly linked list.
Basically traversing means to reach each and every node in the list one after another in the sequence to
perform some operation on that.
T

The following steps considered an algorithm of traversing in linked list:


H

1. Set PTR initialization = HEAD


IG

2. Apply process to pointer PTR


3. Set pointer = PTR-> NEXT
4. Repeat step 2 and 3 up to PTR! = NULL
R

5. Exit
Y

7.4.2 Searching
P

Searching is also a linear linked list in data structure which is used to determine the state of a specific
O

element in the list. In a searching, we want to traverse the comprehensive linked list and start comparing
each node with the data to be explore until a match is found. In case, if the element from the linked list
C

is matched then the position of that element is resumed from the function. When to start the process of
searching from the starting node as random is not possible.
The following steps describe the algorithm of searching in linked list:
1. [Initialization] set PTR = HEAD
2. Repeat up to PTR[ j]! = DATA: j=j+1
3. If j=n+1, then set PTR= 0

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Else PTR= n+1


4. Exit

7.4.3 Insertion
We apply insertion operation on linked list when we want to insert a new node in the list. But for that it is
significant to traverse the list in order one after another to find the position where inserting a new node,
therefore, we will insert a new node on that place. A new node can be entered wherever it is required at
the beginning to the end. An example of inserting a new node at the fort of linked list is shown in Figure 2:

D
E
Start 150 40 300 50 400 60 500 70 NULL

V
200 300 400 500
New Node
Current

R
50 200 Node

E
150

S
figure 2: add New Node at the front
E
When we want to add the new node at a particular position is shown in Figure 3:
R
T

Start 150 40 300 50 400 60 500 70 NULL


H

200 300 400 500


New Node
Current
IG

50 200 Node

150
R

figure 3: add a New Node at a Particular Position


Y

And, if we want to insert a new node at the end of a linked list, an example is shown in Figure 4:
P
O

Start 150 40 300 50 400 60 500 70 NULL


C

200 300 400 500


New Node
Current
50 200 Node

150

figure 4: Inserting New Node at the end

6
UNIT 07: Linked List JGI JAIN
DEEMED-TO-BE UNIVERSITY

7.4.4 deletion
A similar process is required for deletion as same in insertion of traversing a linked list to find the node
to delete. We can delete the node from existing linked list at the beginning to the end. But just a little
adjustment should be required while deleting an element we must adjust the head, pointer to the next
from the existing.

deletion a node from beginning


An example of deleting an existing node from linked list is shown in Figure 5:

D
E
Start

V
R
10 20 30 40 50

E
S
figure 5: Linked List for deletion
E
The first node is deleted from the given linked list is shown in Figure 6:
R
T

Start
H

20 30 40 50
IG
R

figure 6: Linked List after deletion


Y

deleting a node at the middle


An example of deleting node from the middle is shown in Figure 7:
P
O

Start P
C

10 20 30 40 50

figure 7: Linked List after deletion at the Middle

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

deleting a Node at the end


Example of deleting a node at the end of the linked list is shown in Figure 8:

Start P

10 20 30 40 50

D
E
figure 8: Linked List for deletion at the end

V
We want to delete the node p as shown in Figure 8, after deletion at the end the final linked list is shown
in Figure 9:

R
E
Start P

S
E
10 20 30 40
R

figure 9: Linked List after deletion at the end


T

7.5 TyPeS Of LINked LIST


H

A linked list in a data structure is a sequence of node connected to one another by pointers. Linked list is
further classified into four ways are as follows:
IG

1. Singly linked list


2. Doubly linked list
R

3. Circular linked list


4. Header linked list
Y
P

7.5.1 Singly Linked List


O

.In a data structure singly linked list is considered as the collection of set of elements in an organised
manner. In singly linked list the number of elements is required as per the program. It consists a node
can be classified into two parts:
C

1. Data part
2. Link part

In which data part contain the definite information about the node that is to be represented while the
link part consist the address of instant successor. A singly linked list is traversed only in one direction
because each node containing only next pointer. Hence, it is not possible to traverse the linked list in
reverse direction.

8
UNIT 07: Linked List JGI JAIN
DEEMED-TO-BE UNIVERSITY

A singly linked list is shown in Figure 10:

Address of
Value
Next Node
Node

figure 10: Singly Linked List

In a singly linked list the element in a list is connected to each other in such a way that the value of next

D
variable to the last node is NULL is shown in Figure 11:

E
Node

V
R
2 3 6

E
figure 11: NULL to the Linked List

7.5.2 doubly Linked List S


E
A doubly linked list is considered as more complicated than singly linked list because the nodes in doubly
R
linked list comprise a pointer to the succeeding as well as the preceding node in an ordered manner. It
can be traversed in a one as well as in a backward direction. A doubly linked list is shown in Figure 12:
T

Null 5 6 4 Null
H
IG

figure 12: doubly Linked List

7.5.3 circular Linked List


R

It is the process in which the last node comprises the pointer to the front node or first node of the
list is known as circular linked list. Though traversing a circular linked list initiate from any node and
Y

traversed it in any forward and backward direction until we influence the similar node where we started.
P

Thus, it has no starting and no ending. For better understanding the circular linked list considered the
following Figure 13:
O
C

Head

1 Next 2 Next 3 Next

figure 13: circular Linked List

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

7.5.4 Header Linked List


In a linked list a special node that is found at the beginning of the list is known as header linked list and
the node is considered as header node. That is why in a header node ‘start’ is not indicated the first node
of the list but it will consists the address of that node/ header node. However, header linked list is further
classified into two parts as follows:
zz Grounded header linked list
zz Circular header linked list

D
An example of header linked list is shown in Figure 14:

E
Header Node

V
4 99 5 99 37 5 25 Null

R
E
Count of Maximum Minimum
Nodes in List Value in List Value

S
E
figure 14: Header Linked List
R
7.6 LINked STackS aNd QUeUeS
A stack is a linear data structure in which the insertion and deletion of elements is done at only one
end rather than in the middle. It can be executed by using arrays of linear type. It is mostly used in
T

transforming and assessing expression in polish notation.


H

Whereas, a linear stack is a list of elements which is generally executed as a singly linked list, thus it
start pointer plays the role of the top pointer of a stack.
IG

A linear queue is defined as it is represented by using array, in which only finite no of elements can be
inserted using two pointers frONT and rear. The FRONT pointers performs a role of starting node
R

whereas, the REAR pointer is set to play the role at the last node.
The following C++ program is used to implement the linear queue using linked list are as follows:
Y

#include <iostream>
P

using namespace std;


struct node {
O

int data;
struct node *next;
};
C

struct node* Front = NULL;


struct node* Rear = NULL;
struct node* Temperature;
void Insert() {
int val;
cout<<"Enter element in queue : "<<endl;
cin>>val;
if (Rear == NULL) {

10
UNIT 07: Linked List JGI JAIN
DEEMED-TO-BE UNIVERSITY

Rear = (struct node *)malloc(sizeof(struct node));


Rear->next = NULL;
Rear->data = val;
Front = Rear;
} else {
Temperature=(struct node *)malloc(sizeof(struct node));
Rear->next = Temperature;
Temperature->data = val;
Temperature->next = NULL;
Rear = Temperature;

D
}
}

E
void Delete() {
Temperature = Front;

V
if (Front == NULL) {
cout<<"Underflow"<<endl;

R
return;
}

E
else
if (Temperature->next != NULL) {
Temperature = Temperature->next;
S
E
cout<<" Elements delete from the queue: "<<Front->data<<endl;
free(Front);
R
Front = Temperature;
} else {
cout<<"Elements delete from the queue: "<<Front->data<<endl;
T

free(Front);
Front = NULL;
H

Rear = NULL;
}
IG

}
void Display() {
Temperature = Front;
R

if ((Front == NULL) && (Rear == NULL)) {


cout<<"Queue is empty"<<endl;
Y

return;
}
P

cout<<"Queue elements are: ";


while (Temperature != NULL) {
O

cout<<Temperature->data<<" ";
Temperature = Temperature->next;
C

}
cout<<endl;
}
int main() {
int ch;
cout<<"1) Enter element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl;
cout<<"3) Display all elements of queue"<<endl;

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice: "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();

D
break;
case 4: cout<<"Exit"<<endl;

E
break;
default: cout<<"Invalid choice"<<endl;

V
}
} while(ch!=4);

R
return 0;
}

E
The output of given code is as follows:
/tmp/qmuGaeqHMo.o
1) Enter element to queue S
E
2) Delete element from queue
3) Display all elements of queue
R
4) Exit
Enter your choice:
T

1
Enter element in queue:
H

23
Enter your choice:
IG

1
Enter element in queue:
34
Enter your choice:
R

1
Enter element in queue :
Y

56
Enter your choice :
P

3
O

Queue elements are: 23 34 56


Enter your choice :
2
C

Elements delete from the queue: 23


Enter your choice :
4
Exit
The following C++ program is used to implement the linear stack using linked list are as follows:
#include <iostream>
using namespace std;

12
UNIT 07: Linked List JGI JAIN
DEEMED-TO-BE UNIVERSITY

struct Node {
int data;
struct Node *next;
};
struct Node* Top = NULL;
void PUSH(int val) {
struct Node* Newnode = (struct Node*) malloc(sizeof(struct Node));
Newnode->data = val;
Newnode->next = Top;
Top = Newnode;

D
}
void POP() {

E
if(Top==NULL)
cout<<"Stack Underflow"<<endl;

V
else {
cout<<"The popped element is "<< Top->data <<endl;

R
Top = Top->next;
}

E
}
void display() {
struct Node* ptr;
S
E
if(Top==NULL)
cout<<"stack is empty";
R
else {
ptr = Top;
cout<<"Stack elements are: ";
T

while (ptr != NULL) {


cout<< ptr->data <<" ";
H

ptr = ptr->next;
}
IG

}
cout<<endl;
}
R

int main() {
int ch, val;
Y

cout<<"1) Push element in stack"<<endl;


cout<<"2) Pop element from stack"<<endl;
P

cout<<"3) Display all element of stack"<<endl;


cout<<"4) Exit"<<endl;
O

do {
cout<<"Enter choice: "<<endl;
C

cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
PUSH(val);
break;
}

13
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

case 2: {
POP();
break;
}
case 3: {
display();
break;
}
case 4: {

D
cout<<"Exit"<<endl;
break;

E
}
default: {

V
cout<<"Invalid Choice"<<endl;
}

R
}
}while(ch!=4);

E
return 0;
}
The output of given C++ code is as follows: S
E
/tmp/qmuGaeqHMo.o
1) Push element in stack
R
2) Pop element from stack
3) Display all element of stack
4) Exit
T

Enter choice:
H

1
Enter value to be pushed:
IG

12
Enter choice:
1
Enter value to be pushed:
R

16
Enter choice:
Y

1
P

Enter value to be pushed:


28
O

Enter choice:
3
C

Stack elements are: 28 16 12


Enter choice:
2
The popped element is 28
Enter choice:
4
Exit

14
UNIT 07: Linked List JGI JAIN
DEEMED-TO-BE UNIVERSITY

7.7 aPPLIcaTIONS Of LINked LIST


In a data structure, linked list is generally a chain of nodes in which each node is connected to each other
by means of pointers or references. A single node is simply an object that has “data” and a “next” pointer
that points to the next node in a singly or circular linked list, as well as a “previous” pointer that points
to the previous node in a doubly linked list.
Some of the application of linked list is as follows:
zz Execution of stacks and queues.

D
zz Execution of graphs: Adjacency list illustration of graphs is most popular which uses linked list to
store adjacent vertices.

E
zz Dynamic memory allocation: We use linked list of free blocks.
zz Preserving directory of names.

V
zz Executing arithmetic operations on extensive integers.

R
zz Manipulation of polynomials by storing constants in the node of linked list.
Demonstrating sparse matrices.

E
zz

7.8 TIMe cOMPLexITy aNaLySIS Of LINked LIST


S
The time complexity of memory address as we know that to access a definite element, the time complexity
E
is (O ( N ) where N refers to the block of continuous element being read. Linked lists have maximum of
R
their advantage when it comes to the insertion and deletion of nodes in the. Contrasting the dynamic
array, insertion and deletion at any portion of the list takes constant time. In the array, we could at least
have the array sorted. The following time complexity for linked list operations is as follows:
T

zz The time complexity of Indexing - O(n)


H

zz The time complexity of Insertion - O(1)


zz The time complexity of Search - O(n)
IG

zz The time complexity of Deletion - O(1)


R

Lab exercise
7(a). Write a Program in C++ to demonstrate possible operations of Singly Linked List (SLL).
Y

The following C++ program is used to implement the singly linked list are as follows:
P

#include <iostream>
using namespace std;
O

struct Node {
int data;
C

struct Node *next;


};
struct Node* HEAD = NULL;
void insert(int New_data) {
struct Node* New_node = (struct Node*) malloc(sizeof(struct Node));
New_node->data = New_data;
New_node->next = HEAD;
HEAD = New_node;

15
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

}
void display() {
struct Node* pointer;
pointer = HEAD;
while (pointer != NULL) {
cout<< pointer->data <<" ";
pointer = pointer->next;
}
}
int main() {

D
insert(15);
insert(20);

E
insert(25);
insert(30);

V
insert(35);
cout<<"The linked list is: ";

R
display();
return 0;

E
}
The output of given C++ code is as follows:
/tmp/qmuGaeqHMo.o S
E
The linked list is: 35 30 25 20 15
7(b). Write a Program in C++ to demonstrate possible operations of Doubly Linked List (DLL).
R

The following C++ program is used to implement the doubly linked list are as follows:
#include <iostream>
T

using namespace std;


struct Node {
H

int data;
struct Node *Previous;
IG

struct Node *Next;


};
struct Node* HEAD = NULL;
R

void insert(int Newdata) {


struct Node* Newnode = (struct Node*) malloc(sizeof(struct Node));
Y

Newnode->data = Newdata;
Newnode->Previous = NULL;
P

Newnode->Next = HEAD;
if(HEAD != NULL)
O

HEAD->Previous = Newnode ;
HEAD = Newnode;
C

}
void display() {
struct Node* PTR;
PTR = HEAD;
while(PTR != NULL) {
cout<< PTR->data <<" ";
PTR = PTR->Next;
}

16
UNIT 07: Linked List JGI JAIN
DEEMED-TO-BE UNIVERSITY

}
int main() {
insert(30);
insert(25);
insert(18);
insert(16);
insert(12);
cout<<"The doubly linked list is: ";
display();
return 0;

D
}
The output of given C++ code is as follows:

E
/tmp/qmuGaeqHMo.o

V
The doubly linked list is: 12 16 18 25 30

R
Conclusion 7.9 cONcLUSION

E
zz In a data structure, linked list is generally a chain of nodes in which each node is connected to each

zz
other.
S
A list is an ordered datatype, in which the elements are kept in a sequence.
E
zz Memory allocation is the process of storing and preserving a comprehensive and uncomprehensive
R
part of computer memory.
zz Static memory allocation is achieved during compilation.
T

zz Dynamic memory allocation is achieved during the implementation of programming.


A linked list is a linear data structure that involve traverse of node in every state.
H

zz

zz Searching is also a linear linked list in data structure which is used to determine the state of a
specific element.
IG

zz We apply insertion operation on linked list when we want to insert a new node in list.
zz A similar process is required for deletion as same in insertion of traversing.
R

zz In singly linked list the number of elements is required as per the program.
Y

zz A doubly linked list is considered as more complicated than singly linked list.
A circular linked list initiate from any node and traversed it in any direction.
P

zz

zz A special node that is found at the beginning of the list is known as header linked list.
O

zz A linear stack is a list of elements which is generally executed as a singly linked list.
A linear queue is defined as it is represented by using array.
C

zz

7.10 GLOSSary

zz Linked list: It is generally a chain of nodes in which each node is connected to each other.
zz List: It is an ordered datatype, in which the elements are kept in a sequence.

17
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz Memory allocation: It is the process of storing and preserving a comprehensive and uncomprehensive
part of computer memory.
zz Static memory allocation: It is achieved during compilation.
zz dynamic memory allocation: It is achieved during the implementation of programming.
zz Searching: It is a linear linked list in data structure which is used to determine the state of a specific
element.
zz Insertion: It is used to insert a new node in list.

D
zz deletion: It is required for deletion as same in insertion of traversing.
zz Singly linked list: It is a number of elements are required as per the program.

E
zz doubly linked list: It is considered as more complicated than singly linked list.

V
zz circular linked list: It initiates from any node and traversed it in any direction.
zz Header linked list: It is a special node that is found at the beginning of the list.

R
zz Linear queue: It is defined as it is represented by using array.

E
7.11 SeLf-aSSeSSMeNT QUeSTIONS
S
E
a. Multiple choice Questions
R
1. A __________ is an ordered datatype in which the elements are kept in a sequence.
a. List b. Operations
c. Memory d. Queue
T

2. A linked list is __________ in nature.


H

a. Static b. Dynamic
IG

c. Finite d. Circular
3. __________ is the process of storing and preserving a comprehensive and uncomprehensive part of
computer memory for the implementation of programs.
R

a. Linked list b. Queue


c. Memory allocation d. Stacks
Y

4. Before the implementation of any process it must be first located in the __________.
P

a. List b. Queue
O

c. Stacks d. Memory
5. Which of these is a memory allocation is achieved during compilation?
C

a. Dynamic memory b. Static memory


c. Linear queue d. Linear stack
6. Which among the following linked list operation is used to determine the state of a specific element
in the list?
a. Traversing b. Insertion
c. Deletion d. Searching

18
UNIT 07: Linked List JGI JAIN
DEEMED-TO-BE UNIVERSITY

7. We can __________ the node from existing linked list at the beginning to the end.
a. Delete b. Insert
c. Search d. Traverse
8. In a data structure a linked list is further divided into __________ parts.
a. 1 b. 2
c. 4 d. 5
9. A linear queue is defined as it is represented by using __________.

D
a. Stacks b. List
c. Memory d. Array

E
10. Which among the following in a linked list is a special node that is found at the beginning of the list?

V
a. Circular linked list b. Header linked list
c. Doubly linked list d. Singly linked list

R
B. essay Type Questions

E
1. In a data structure, linked list is generally a chain of nodes. What is a linked list in data structure?

S
2. Before the implementation of any process it must be first located in the memory. Describe the
E
concept of memory allocation with its types.
3. A linked list is a linear data structure that involve traverse of node in every state of singly linked list.
R
Explain various types of linked list operations in brief.
4. A linked list in a data structure is a sequence of node. Evaluate the concept of types of linked list in
T

detail.
5. A stack is a linear data structure in which the insertion and deletion of elements is done at only one
H

end rather than in the middle. Determine the importance of linear stack and queue in linked list.
IG

7.12 aNSwerS aNd HINTS fOr SeLf-aSSeSSMeNT QUeSTIONS


R

a. answers to Multiple choice Questions


Y

Q. No. answer
P

1. a. List
O

2. b. Dynamic
3. c. Memory allocation
C

4. d. Memory
5. b. Static memory
6. d. Searching
7. a. Delete
8. c. 4

19
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Q. No. answer
9. d. Array
10. b. Header linked list

B. Hints for essay Type Questions


1. In a data structure, linked list is generally a chain of nodes in which each node is connected to each
other by means of pointers or references.

D
Refer to Section Introduction
2. Memory allocation is the process of storing and preserving a comprehensive and uncomprehensive

E
part of computer memory for the implementation of programs and procedures.
Refer to Section Memory Allocation

V
3. In data structure, there are linked list operations which allow us to perform distinct action on linked

R
list. Some of the linked list operations are as follows:
z Traversing

E
z Searching
z Insertion
Deletion
S
E
z

Refer to Section Linked List Operations


R
4. A linked list in a data structure is a sequence of node connected to one another by pointers. Linked
list is further classified into four ways:
T

Refer to Section Types of Linked List


5. A linear stack is a list of elements which is generally executed as a singly linked list, thus it start
H

pointer plays the role of the top pointer of a stack.


IG

Refer to Section Linked Stacks and Queues

@ 7.13 POST-UNIT readING MaTerIaL


R

[Link]
Y

zz

zz [Link]
P
O

7.14 TOPIcS fOr dIScUSSION fOrUMS


C

zz Disucss the concept of linked list, its representation and its types with your friends and classmates.
Also discuss the linear array and stack with real world examples.

20
UNIT

08

D
E
Trees

V
R
E
Names of Sub-Units S
E
Introduction to Tree, Definition of a Tree, Tree Terminology, Binary Tree, Complete Binary Tree,
R
Properties of Binary Tree, Array and Linked Representation of Binary Trees, Binary Tree Traversals,
Additional Binary Tree Operations, Threaded Binary Trees, Binary Search Trees, Application of Trees,
Evaluation of Expression.
T
H

Overview
IG

This unit begins by discussing about the concept of tree, tree terminology, binary tree and complete
binary tree. Next, the unit discusses the properties of binary tree, array and linked representation of
binary trees and binary tree traversals. Further the unit explains the additional binary tree operations,
R

threaded binary trees and binary search trees. Towards the end, the unit discusses the application of
trees and evaluation of expression.
Y
P

Learning Objectives
O

In this unit, you will learn to:


a Discuss the concept of tree, tree terminology, binary tree and complete binary tree
C

a Explain the concept of properties of binary tree, array and linked representation of binary trees
a Describe the binary tree traversals, additional binary tree operations and threaded binary trees
a Explain the significance of binary search trees and application of tress
a Discuss the concept of evaluation of expression
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit you would:


a Evaluate the concept of tree, tree terminology, binary tree and complete binary tree
a Assess the concept of properties of binary tree, array and linked representation of binary trees
a Evaluate the importance of binary tree traversals, additional binary tree operations and threaded
binary trees
Determine the significance of binary search trees and application of tress

D
a

a Explore the concept of evaluation of expression

E
V
Pre-Unit Preparatory Material

R
a [Link]

E
8.1 INTRODUCTION
S
A distinct data structure where hierarchical relationships exist among the data items or nodes is referred
as Trees. It is a non-linear hierarchical data structure which includes a group of objects called as nodes.
E
These nodes connected with one another in a tree using “edges”. Due to the non-linear structure of trees
R
it increases the process of storing, retrieving and manipulation of data by using innovative methods. A
tree in which each node of a tree comprises data and positions. It is genuine that there is a tree it must
have a root node. That root node is the topmost node in a hierarchy of tree. A tree is called a tree when
T

it having a one root node, sub-node, parent node and a child node. All these nodes together make a tree.
A tree is shown in Figure 1:
H

Root
IG
R

A Level 0
Y

B C Level 1
P

Parent Node Level 2


D E F G
O

Siblings

Child Node
C

H I J Level 3

Sub-tree Leaf Node

Figure 1: Tree

2
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

8.2 DEFINITION OF TREE


A tree refers to an inter linked open chain adrift graph. The Count of the edges in a tree consisting N
vertices is N-1. The vertex with degree 0 is addressed as the root. A leaf node in a tree is considered as
when its vertex has degree one. The internal nodes have degree starting from 2. A Decision tree is a
specialised tree where each internal node indicates a trial or criteria on a anticipative variable. The
edges provide feasible solutions to the trials. The leaf node provides the results of all trials conducted on
a pathway. Such trees are widely used in predictive modelling. The leaf node in a tree is shown in Figure
2:

D
E
V
R
E
Figure 2: Leaf Nodes
S
A tree is known to consist hierarchical data. If you wish to display the details of the employees and their
E
designations in a hierarchical manner as shown in Figure 3:
R

John
T

Steve Rohan
H
IG

Lee Bob Eila Sal Emma


R

Tom Raj
Y
P

Bill
O

Figure 3: Tree having Hierarchical Data


C

The image depicts the administrative hierarchy of a [Link] is acting CEO. Steve and Rohan are
the subordinates of John. Lee, Bob, Ella are the supervisees of Steve. Sal and Emma are the subordinates
of Rohan. Tom and Raj are the supervisees of Emma. Bill is a subordinate of Tom. Such rational design
pattern or formation is known as Tree. Hair the topmost vertex act as root and all the edges are the
branches going in the descending direction. This trees act as an efficient data structure to hold the
hierarchical data.

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

8.3 TREE TERMINOLOGY


In a Tree, Every distinct element is known as node. Node in a tree data structure stores the actual
data of that specific element and connects to next element in hierarchical manner. An example of tree
terminology is shown in Figure 4:

Child

D
Parent Siblings

Degree

E
Edge

V
Root Internal
Node

R
Tree Terminology
Leaf

E
Forest Node

Subtree S Level
E
Depth Height
R
T

Figure 4: Tree Terminology


H

Some of the terminologies in a tree are as follows:


IG

zz Root: A root node is an exclusive node in the tree in which other subtrees were connected. It has its
child in left and right of the tree as shown in Figure 5:
R

Root Node

A
Y
P

B C
O
C

D E F G H

J J K

Figure 5: Root Node

4
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Edge: In a tree each node is connected with one another through a link is known as “edge”. It connects
each and every node either it has child or not is shown in Figure 6:

Edges
A

B C

D
D E F G H

E
J J K

V
Figure 6: Edge in a Tree

R
zz Parent: In a tree a node which having one or more child is termed as parent node. It has any number
of child nodes in a tree is shown in Figure 7:

E
A S Parent of B and C
E
B C
R
T

D E F G H
H

J J K
IG

Figure 7: Parent Node

In the above figure, A tree in which A is a parent of (B & C) node, B is a parent of (D, E & F) and so on.
R

zz Child: In a tree any sub node of a given node is called child node and all the nodes in a tree except
Y

root node are child nodes as shown in Figure 8:


P

A Child of A
O

B C
C

Child of B

D E F G H

J J K

Figure 8: Child Node

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz Siblings: In a tree a node which belongs to the same parent node is called siblings node as shown in
Figure 9:

B C

D
E
D E F G H

V
J J K

R
E
Siblings

Siblings
S
E
R
Figure 9: Siblings Node

zz Degree: A degree determines the total number of child of a node. It depicts the highest degree of the
T

node among all the nodes in a tree as shown in Figure 10:


H

Degree (B) = 3
Degree (C) = 2
IG

A
R

B C
Y
P
O

D E F G H
C

J J K

Figure 10: Degree of a Tree

6
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Internal node: In a hierarchy of a tree it is not mandatory that the entire parent node comprises two
or more child; some of them having only one child node such node is called as internal node or non-
terminal nodes as shown in Figure 11:

Internal Node
A Internal Node

B C

D
D E F G H

E
J J K

V
R
Figure 11: Internal Node

Leaf node: In a tree such type of nodes with no child also exists is known as leaf node. These nodes

E
zz
also called as external or terminal nodes of a tree as shown in Figure 12:

A S
E
B C
R

D E F G H
T
H

J J K
Leaf Node
IG

Leaf Node

Figure 12: Leaf Node


R

zz Level: In a tree data structure is a step-by-step process of measuring a tree from top to bottom. The
first level of a tree count start from 0 and it increases by 1 on each step as shown in Figure 13:
Y
P

A Level 0
O

B C Level 1
C

D E F G H Level 2

J J K Level 3

Figure 13: Level of a Tree

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz Height: The total number of edges on the longest path from leaf node to a specific node is called
height. It is also considered as the maximum level of a tree as shown in Figure 14:

Height (B) = 2 A

B C Height (H) = 0

D
D E F G H

E
J J K

V
Figure 14: Height of a Tree

R
zz Depth: In a hierarchy of tree the total number of edges that connects root node to the leaf node in

E
the downward path is known as depth as shown in Figure 15:

Depth (B) = 1 A S
E
B C
R
Depth (H) = 2

D E F G H
T
H

J J K
IG

Figure 15: Depth of a Tree


R

zz Subtree: In a tree a node with a child of a node and form another tree is known as subtree. In a
subtree every child node has a parent as shown in Figure 16:
Y

A
P

Sub
O

B C trees
C

D E F G H

J J K

Figure 16: Subtree

8
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Forest: It is a collection of those trees which are not joint together or we can say it has a group of
disjoint trees as shown in Figure 17:

B C

D E F G H

J J K

D
Figure 17: Forest

E
8.4 BINARY TREE

V
In a data structure a binary tree is a distinct type of tree as by the name binary that means two, every

R
node or vertex in a tree has either zero, one and two child one. But in a binary tree is an important
session of a tree data structure in which a node at most having two child nodes or we can say that every

E
parent node in a binary tree can have only two children maximally. It is not a linear data structure like
queues, linked list and arrays etc. it is a hierarchical data structure instead of that.
In a binary tree all the nodes have three main components are as follows: S
E
zz Data element
R
zz Right pointer
zz Left pointer
T

A binary tree is shown in Figure 18:


H

1
IG

2 3
R

5 6
Y

Figure 18: Binary Tree


We can have the following analytical depiction of the above binary tree where the nodes resemble the
P

nodes of a linked list as shown in Figure 19:


O

1
C

2 3

5 6

Figure 19: Nodes of a Linked List

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Here, Node 1 has dual pointers, left and right directing to the corresponding left and right nodes.
Similarly node 2 has two pointers as well. Nodes 3, 5 and 6 have NULL pointers in their left and right
portions as they are leaf nodes.

8.5 COMPLETE BINARY TREE


As a binary tree, a complete binary tree is a tree in which each and every level of a tree is completely
filled except the last level of a complete binary tree. Completing of each level determines that every
parent node should have exactly two child node. A parent node that doesn’t have its left and right node
is not defined as complete binary tree. Although, a binary tree to fulfil the requirement in order to be a

D
complete binary tree is that the last level of a tree contain all the keys as left as possible. It means that a
parent node on the last level of (CBT) but it should have a child node on the left only.

E
A complete binary tree differs from the full binary tree in ways as follows:

V
zz Every leaf node must incline around the left.
The final leaf node may lack its right sibling. In other words, a complete binary tree need not be a

R
zz
full binary tree.

E
A complete binary tree is shown in Figure 20:

1
S
E
R
2 3
T

4 5 6
H

Figure 20: Complete Binary Tree


IG

8.6 PROPERTIES OF TREE


R

The following points describe the properties of tree are as follows:


zz The total count of nodes at a level i is given by 2i.
Y

zz The lengthiest way from the root to the leaf node is called Height of a tree. The tree displayed above
has height of 3. Hence the total count of nodes at height 3 is given by (1+2+4+8) = 15. In general, the
P

total count of nodes at height h is (20 + 21 + 22+….2h) = 2h+1 -1.


O

zz The least count of nodes at height h is given by h+1.


zz The presence of least count of node indicates greatest height, whereas the presence of greatest count
C

of nodes indicates least height in a tree.


If a binary tree has a node count of n then determines the following points:
zz We can calculate the least or minimum height
We are aware as:
n = 2h+1 -1
n+1 = 2h+1

10
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

Applying log on both sides of the equation as:


log2 (n+1) = log2 (2h+1)
log2 (n+1) = h+1
h = log2 (n+1) - 1
zz The overall height is calculated
We are aware that:
n = h+1

D
h= n-1

E
8.7 ARRAY AND LINKED LIST REPRESENTATION OF BINARY TREE

V
A tree in a data structure which has a distinct type of tree, every parent node should have exactly two
child nodes is knows as binary tree. It is represented in a hierarchal manner. Now, how we can represent

R
the binary tree in a computer memory. It can be represented in the two ways are as follows:
zz Representing through array

E
zz Representing through linked list
Let’s have a look at the tree as shown in Figure 21:
S
E
A
R

B C
T

D F G H
H

I J K
IG

Figure 21: A Tree


R

8.7.1 Representing Binary Tree through Array


While representing a binary tree using array firstly we require converting that binary tree into a full
Y

binary tree and provide number to each and every node to store in an array in their respective order. Fig
21 is converted into a full binary tree is shown in Figure 22:
P
O

A
C

B C

D F G H

I J K

Figure 22: Full Binary Tree

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The full binary tree is now represented through array as shown in Figure 23:

A B C D F G H I J - - - K - - - - - - - -

Figure 23: Array represents Binary Tree

D
8.7.2 Representing Binary Tree through Linked List
When binary tree is represented through linked list is stored in the memory as linked lists. In linked list

E
the nodes are not kept at adjacent memory location as shown in Figure 24:

V
R
Root Node

E
A

S
E
R
B C
T

D NULL F NULL NULL G NULL H NULL


H
IG

NULL I NULL NULL J NULL NULL K NULL


R
Y

Figure 24: Linked List Represents Binary Tree


P

8.8 BINARY TREE TRAVERSAL


O

Binary tree traversal in data structure is the process of visiting, updating and verifying once each node
of a tree. Linear data structures such as arrays, stacks, queues, and linked list possess uni-directional
C

paths to scan the information. However we have multiple pathways to scan the information present in
the hierarchical data structures like trees. We can perform distinct tree traversal in data structure in
many ways. Some of them are as follows:
zz In-order traversal
zz Post-order traversal
zz Pre-order traversal

12
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

8.8.1 In-Order Traversal


An in-order traversal, always start visiting from the left subtree then it visit to root node and after the
right subtree as shown in Figure 25:

Root

D
A
1
3

E
B C

V
2 2

R
E
D E F G
1 3 1 3

Left Subtree S
Right Subtree
E
Figure 25: In-order traversal in Binary Tree
R

8.8.2 Post-Order Traversal


T

In the post-order traversal the process of visiting starts from left subtree of a tree, then it visit to the
right subtree and later it visit to root node as shown in Figure 26:
H

Root
IG
R

3
A
1
2
Y
P

B C
3 3
O
C

D E F G
1 2 1 2

Left Subtree Right Subtree

Figure 26: Post-order Traversal in Binary Tree

13
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

8.8.3 Pre-Order Traversal


In the pre-order traversal is just opposite to the post-order traversal, in which firstly we visit to the root
node then to the left subtree and then finally to the right subtree of a binary tree as shown in Figure 27:

Root

D
A
2
3

E
V
B C
1 1

R
E
2
D
3
E
2 S
F
3
G
E
Left Subtree Right Subtree
R

Figure 27: Pre-order Traversal in Binary Tree


T

8.9 ADDITIONAL BINARY TREE OPERATIONS


H

Some of the most common additional binary tree operations are as follows:
IG

zz Depth-first order
z Breadth-first order
R

8.9.1 Depth-first Order


Y

In this technique, we initiate by meeting the remotest node w.r.t the root node, which must be a child of a
previously seen node. We need not recollect the seen nodes, since a tree should not have cycles. Pre-order
P

traversal is a noteworthy illustration of depth first travel. We can refer depth-first search for further
clarity.
O

8.9.2 Breadth-first Order


C

Any alternative name of this traversal is level-order traversal. Considering a complete binary tree,
the width-index of a node given by (i - (2d - 1)) is utilised for noting the travelling directions from root
node. For achieving this, scan bitwise sinistrodextraly, initiating from bit d - 1, where d denotes the
distance between the root and node, (d = floor (log2 (i+1))). If we mask the width-index at bit d - 1, the bit
becomes 0 and if it is 1, then we need to move either left or right, accordingly. The verification goes on
by consecutive examination of the upcoming bits from left to right till all the nodes are visited. The last
travel from a parent node to a child node is given by the rightmost bit.

14
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

8.10 THREADED BINARY TREE


As we know that the binary tree nodes have exactly two children but in the case of having only one child
or no child node, the link part in the linked list representation remains NULL. The threaded binary tree
helps to reuse that vacant links again by making some threads. If a vacant left or right child area one
node has then it will be used as thread. And if in the left threaded mode of a tree if some node without left
child node then the left pointer will point out to its in-order predecessor, similarly in the right threaded
tree if some node without any child node then the right pointer will point out to its in-order successor. If
there is no successor or predecessor is existing in both the cases then it will point to the header node of
a tree. A threaded binary tree is shown in Figure 28:

D
E
1

V
R
2 C

E
4 4
S 6
E
R
Figure 28: Threaded Binary Tree

A threaded binary tree is further divided into two parts as:


T

zz Single threaded: In the single threaded binary tree only the NULL pointer of right subtree is pointed
to in order successor as shown in Figure 29:
H
IG

A
R

Single Threaded
Binary Tree
Y

B E
P
O

C
C

Figure 29: Single Threaded Binary Tree

15
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz Double threaded: In the double threaded binary tree both the right and left NULL pointer pointed to
in order successor or predecessor as shown in Figure 30:

B C

D
D E F

E
V
G H I

R
Figure 30: Double Threaded Binary Tree

E
8.11 BINARY SEARCH TREE S
E
A binary search tree is a special type of binary tree that contains a definite order of elements in it. In a
BST The elements of the left subtree has a lesser value then the parent node value whereas, the elements
R
of the right subtree may have greater value then the parent node value. A BST is also known as sorted
or ordered binary tree. It does not contain any duplicate nodes in a tree. A binary search tree is shown
in Figure 31:
T
H

110
IG

90 125
R

80 95 100 130
Y
P

92 132
O

Figure 31: Binary Search Tree (BST)


C

Some of the most common operations in binary search tree are as follows:
zz Insertion
zz Deletion
zz Searching

16
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

8.11.1 Insertion
This is the common operations used in BST used to insert values in a tree. While inserting values insides
the tree make sure that the order of the values is not disturbed.
The following C++ program is used to perform insertion operation in BST are as follows:
// C++ program to demonstrate insertion
// in a Binary Search Tree recursively.
#include <iostream>
using namespace std;

D
class BST

E
{
int Data;

V
BST *Left, *Right;

R
public:
BST();

E
BST(int);
BST* Insert(BST*, int);

};
void Inorder(BST*);
S
E
BST ::BST()
: Data(0)
R

, Left(NULL)
, Right(NULL)
T

{
}
H

BST ::BST(int Value)


{
IG

Data = Value;
Left = Right = NULL;
}
BST* BST ::Insert(BST* Root, int Value)
R

{
if (!Root)
Y

{
// Insert the first node, if root is NULL.
P

return new BST(Value);


O

}
if (Value > Root->Data)
{
C

Root->Right = Insert(Root->Right, Value);


}
else
{
Root->Left = Insert(Root->Left, Value);
}
return Root;

17
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

}
void BST ::Inorder(BST* Root)
{
if (!Root) {
return;
}
Inorder(Root->Left);
cout << Root->Data << endl;
Inorder(Root->Right);
}

D
int main()
{

E
BST b, *Root = NULL;
Root = [Link](Root, 30);

V
[Link](Root, 35);
[Link](Root, 28);

R
[Link](Root, 56);
[Link](Root, 68);

E
[Link](Root, 75);
[Link](Root, 99);
[Link](Root); S
E
return 0;
}
R
The output of given C++ code is as follows:
/tmp/52OYpsDV3o.o
T

28
30
H

35
56
IG

68
75
99
R

8.11.2 Deletion
Y

In a binary search tree deletion operation is used when we require removing a node from the tree. In the
deletion operation firstly identifies the node and its location for deletion. A node should be a lead node.
P

The following C++ program is used to perform deletion operation in BST


O

#include<stdio.h>
#include<stdlib.h>
struct Node{
C

int key;
struct Node *Left, *Right;
};
struct Node *newNode(int item){
struct Node *Temperature = (struct Node *)malloc(sizeof(struct Node));
Temperature->key = item;
Temperature->Left = Temperature->Right = NULL;
return Temperature;

18
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

}
void inordertraversal(struct Node *root){
if (root != NULL){
inordertraversal(root->Left);
printf("%d ", root->key);
inordertraversal(root->Right);
}
}
struct Node* insert(struct Node* node, int key){
if (node == NULL) return newNode(key);

D
if (key < node->key)
node->Left = insert(node->Left, key);

E
else
node->Right = insert(node->Right, key);

V
return node;
}

R
struct Node * minValueNode(struct Node* node){
struct Node* current = node;

E
while (current && current->Left != NULL)
current = current->Left;
return current; S
E
}
struct Node* deleteNode(struct Node* root, int key){
R
if (root == NULL) return root;
if (key < root->key)
root->Left = deleteNode(root->Left, key);
T

else if (key > root->key)


root->Right = deleteNode(root->Right, key);
H

else{
if (root->Left == NULL){
IG

struct Node *Temperature = root->Right;


free(root);
return Temperature;
R

}
else if (root->Right == NULL){
Y

struct Node *Temperature = root->Left;


free(root);
P

return Temperature;
}
O

struct Node* Temperature = minValueNode(root->Right);


root->key = Temperature->key;
C

root->Right = deleteNode(root->Right, Temperature->key);


}
return root;
}
int main(){
struct Node *root = NULL;
root = insert(root, 25);
root = insert(root, 45);
root = insert(root, 28);

19
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

root = insert(root, 55);


root = insert(root, 67);
root = insert(root, 78);
root = insert(root, 88);
printf("Inorder traversal of a tree \n");
inordertraversal(root);
printf("\nDelete 20\n");
root = deleteNode(root, 55);
printf("Inorder traversal of tree after modification \n");
inordertraversal(root);

D
printf("\nDelete 30\n");
root = deleteNode(root, 78);

E
printf("Inorder traversal of tree after modification \n");
inordertraversal(root);

V
printf("\nDelete 50\n");
root = deleteNode(root, 25);

R
printf("Inorder traversal of tree after modification \n");
inordertraversal(root);

E
return 0;
}
The output of given C++ code is as follows: S
E
/tmp/52OYpsDV3o.o
Inorder traversal of a tree
R

25 28 45 55 67 78 88
Delete 20
T

Inorder traversal of tree after modification


25 28 45 67 78 88
H

Delete 30
Inorder traversal of tree after modification
IG

25 28 45 67 88
Delete 50
Inorder traversal of tree after modification
28 45 67 88
R

8.11.3 Searching
Y

Searching is the process of identifying a particular element or item as “key” in BST. It is one of the easiest
P

operations among others as we do not need to search the entire tree. We just have to match the key in
BST.
O

The following C++ program is used to perform the delete operation in BST are as follows:
C

#include<stdio.h>
#include<stdlib.h>
struct node{
int key;
struct node *Left, *Right;
};
struct node *newNode(int item){
struct node *temperature = (struct node *)malloc(sizeof(struct node));

20
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

temperature->key = item;
temperature->Left = temperature->Right = NULL;
return temperature;
}
void traversetree(struct node *root){
if (root != NULL){
traversetree(root->Left);
printf("%d \t", root->key);
traversetree(root->Right);
}

D
}
struct node* search(struct node* root, int key){

E
if (root == NULL || root->key == key)
return root;

V
if (root->key < key)
return search(root->Right, key);

R
return search(root->Left, key);
}

E
struct node* insert(struct node* node, int key){
if (node == NULL) return newNode(key);
if (key < node->key) S
E
node->Left = insert(node->Left, key);
else if (key > node->key)
R
node->Right = insert(node->Right, key);
return node;
}
T

int main(){
struct node *root = NULL;
H

root = insert(root, 23);


insert(root, 10);
IG

insert(root, 18);
insert(root, 22);
insert(root, 34);
R

insert(root, 47);
insert(root, 87);
Y

printf("The elements in the tree is :\n");


traversetree(root);
P

printf("\nSearching for 34 in this tree ");


if(search(root , 34))
O

printf("\nelement found");
else
C

printf("\nelement not found");


return 0;
}
The output of given C++ code is as follows:
/tmp/52OYpsDV3o.o
The elements in the tree is :
10 18 22 23 34 47 87

21
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Searching for 34 in this tree


element found

8.12 APPLICATION OF TREES


The following points describe the applications of trees are as follows:
zz It is utilized in maintaining the structure of the files, any company,the XML HTML information as it
holds the information hierarchically.
zz Heap is a is a specialized tree utilized to manipulate the arrays and priority queues.

D
zz B-Tree and B+ Tree are utilised to create and manipulate the catalogues in the databases.
zz Syntax Tree finds its application in Compilers.

E
zz K-D Tree is a tree which partitions the space is utilized to arrange points in space with N dimensions.

V
zz Tries are utilised to manipulate dictionaries with options to find the prefixes.
Suffix Trees are used for faster pattern recognition in a String.

R
zz

zz The Smallest path trees and the spanning trees find the application in routers and bridges existing

E
in computer networks.

8.13 EVALUATION OF EXPRESSION S


E
In a binary tree, a tree in which internal node link to the operator and each leaf node link to the operand.
For example an expression is 4 + ((9+3)*5) is shown in Figure 32:
R
T

+
H

4 *
IG

+ 5
R
Y

9 3
P
O

Figure 32: Expression Tree


C

Lab Exercise
Write a Program in C++ to implement Binary Search Tree (BST).
The following C++ program is used to implement the binary search tree are as follows:
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;

22
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

struct node *Left;


struct node *Right;
};
void Inordertraversal(struct node* node, int inorder[], int *index_ptr){
if (node == NULL)
return;
Inordertraversal(node->Left, inorder, index_ptr);
inorder[*index_ptr] = node->data;
(*index_ptr)++;
Inordertraversal(node->Right, inorder, index_ptr);

D
}
int countNodes(struct node* Root){

E
if (Root == NULL)
return 0;

V
return countNodes (Root->Left) +
countNodes (Root->Right) + 1;

R
}
int compare (const void * a, const void * b){

E
return( *(int*)a - *(int*)b );
}
S
void arrayToBST (int *arr, struct node* Root, int *index_ptr){
E
if (Root == NULL)
return;
R
arrayToBST (arr, Root->Left, index_ptr);
Root->data = arr[*index_ptr];
(*index_ptr)++;
T

arrayToBST (arr, Root->Right, index_ptr);


}
H

struct node* newNode (int data){


struct node *temperature = new struct node;
IG

temperature->data = data;
temperature->Left = NULL;
temperature->Right = NULL;
R

return temperature;
}
Y

void printInorder (struct node* node){


if (node == NULL)
P

return;
printInorder (node->Left);
O

printf("%d ", node->data);


printInorder (node->Right);
C

}
int main(){
struct node *Root = NULL;
Root = newNode(20);
Root->Left = newNode(23);
Root->Right = newNode(20);
Root->Left->Left = newNode(18);

23
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Root->Right->Right = newNode(9);
printf("Inorder Traversal of the binary Tree: \n");
printInorder (Root);
int n = countNodes(Root);
int *arr = new int[n];
int j = 0;
Inordertraversal(Root, arr, &j);
qsort(arr, n, sizeof(arr[0]), compare);
j = 0;
arrayToBST (arr, Root, &j);

D
delete [] arr;
printf("\nInorder Traversal of the converted BST: \n");

E
printInorder (Root);
return 0;

V
}

R
The output of given C++ code is as follows:
/tmp/Vg1XaDmN4d.o

E
Inorder Traversal of the binary Tree:
18 23 20 20 9
Inorder Traversal of the converted BST:
9 18 20 20 23
S
E
8.14 CONCLUSION
R
Conclusion

zz A Distinct data structure where hierarchical relationships exist among the data items or nodes is
T

referred as Trees.
H

zz The nodes of a tree are connected with one another in a tree using “edges”.
zz A root node is an exclusive node in the tree.
IG

zz A binary tree is a distinct type of tree in which a parent node has exactly two child nodes.
zz A complete binary tree is a tree in which each and every level of a tree is completely filled except the
last level.
R

zz Representing a binary tree using array firstly we require converting that binary tree into a full
Y

binary tree.
Binary tree is represented through linked list is stored in the memory as linked lists.
P

zz

zz Binary tree traversal in data structure is the process of visiting, updating and verifying once each
O

node of a tree.
zz An in-order traversal, always start visiting from the left subtree.
C

zz post-order traversal the process of visiting starts from left subtree of a tree, then it visit to the right
subtree.
zz Pre-order traversal is just opposite to the post-order traversal, in which firstly we visit to the root
node.
zz Threaded binary tree helps to reuse that vacant links again by making some threads.
zz A binary search tree is a special type of binary tree that contains a definite order of elements in it.

24
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

8.15 GLOSSARY

zz Tree: It is a distinct data structure where hierarchical relationships exist among the data items.
zz Edge: The nodes of a tree are connected with one another in a tree using “edges”.
zz Binary tree: It is a distinct type of tree in which a parent node has exactly two child nodes.
zz Complete binary tree: It is a tree in which each and every level of a tree is completely filled except
the last level.

D
zz Binary tree traversal: It is the process of visiting, updating and verifying once each node of a tree.
In-order traversal: It always starts visiting from the left subtree.

E
zz

zz Post-order traversal: It is the process of visiting starts from left subtree of a tree, then it visit to the

V
right subtree.
Pre-order traversal: It is just opposite to the post-order traversal, in which firstly we visit to the root

R
zz
node.

E
zz Threaded binary tree: It helps to reuse the vacant links again by making some threads.
zz Binary search tree (BST): It is a special type of binary tree that contains a definite order of elements
in it. S
E
zz Path: It is the way or edges consisting a series of nodes required to be visited to reach to any specific
node from the source node.
R

zz Root : It is the originating node from which other nodes emerges. There is always one root in any
tree.
T

zz Parent node: It is the alternative nodes other than the root node, which have sub nodes or child.
Child node: It is the sub node connected to of origin through an edge.
H

zz

zz Leaf node: It is the node that lacks a child node.


IG

8.16 SELF-ASSESSMENT QUESTIONS


R

A. Multiple Choice Questions


Y

1. A Distinct data structure where hierarchical relationships exist among the data items or nodes is
referred as __________.
P

a. Trees
O

b. BST
c. Binary tree
C

d. CBT
2. Which among the following is a step-by-step process of measuring a tree from top to bottom in a tree
terminology?
a. Root
b. Leaf node

25
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

c. Level
d. Degree
3. A __________ is a tree in which each and every level of a tree is completely filled except the last level
of a tree.
a. Binary search tree
b. Binary tree
c. Threaded binary tree

D
d. Complete binary tree
4. Which among the following when representing binary tree first we need to converted binary tree

E
into a full binary tree?
a. Linked list

V
b. Array

R
c. Stacks
d. Queues

E
5. ___________ is the process of visiting, updating and verifying once each node of a tree.
a. Binary tree traversal S
E
b. Complete binary tree
c. Threaded binary tree
R

d. Binary search tree


6. Which of these is the process of visiting starts from left subtree of a tree, then it visit to the right
T

subtree and later it visit to root node?


H

a. In-order traversal
b. Pre-order traversal
IG

c. Data element
d. Post-order traversal
R

7. In which of these we make use of vacant links in linked nodes?


a. Complete binary tree
Y

b. Threaded binary tree


P

c. Binary tree
O

d. Binary search tree


8. A threaded binary tree is further divided into ____________ parts.
C

a. 1
b. 3
c. 4
d. 2

26
UNIT 08: Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

9. ____________ is the process of identifying a particular element or item as “key” in BST.


a. Insertion
b. Deletion
c. Searching
d. Depth first order
10. In which among the following tree both the right and left NULL pointer pointed to in order successor
or predecessor?

D
a. Double threaded binary tree
b. Single threaded binary tree

E
c. Complete binary tree

V
d. Binary search tree

R
B. Essay Type Questions
1. A Distinct data structure where hierarchical relationships exist among the data items. What do you

E
understand by the tree in data structure?

S
2. In a Tree, Every distinct element is known as node. Describe the concept of tree terminology in brief.
3. Completing of each level determines that every parent node should have exactly two child node.
E
Determine the concept of complete binary tree and how it differs from binary tree.
R
4. Binary tree traversal in data structure is the process of visiting and updating each node. What do
you understand by binary tree traversal? Also, discuss its distinct ways for traversing a tree in brief.
5. The threaded binary tree helps to reuse that vacant links again by making some threads. Explain
T

threaded binary tree and its types in detail.


H

8.17 ANSWERS AND HINTS FOR SELF-ASSESSMENT QUESTIONS


IG

A. Answers to Multiple Choice Questions


R

Q. No. Answer
Y

1. a. Trees
P

2. c. Level
O

3. d. Complete binary tree


C

4. b. Array

5. a. Binary tree traversal

6. d. Post-order traversal

7. b. Threaded binary tree

27
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Q. No. Answer

8. d. 2

9. c. Searching

10. a. Double threaded binary tree

B. Hints for Essay Type Questions


1. A Distinct data structure where hierarchical relationships exist among the data items or nodes is

D
referred as Trees. It is a non-linear hierarchical data structure which includes a group of objects
called as nodes. Refer to Section Introduction

E
2. In a Tree, Every distinct element is known as node. Node in a tree data structure stores the actual
data of that specific element and connects to next element in hierarchical manner. Refer to Section

V
Tree Terminology

R
3. As a binary tree, a complete binary tree is a tree in which each and every level of a tree is completely
filled except the last level of a complete binary tree. Refer to Section Complete Binary Tree

E
4. It is the process of visiting, updating and verifying once each node of a tree. Linear data structures
such as arrays, stacks, queues, and linked list possess uni-directional paths to scan the information.
Refer to Section Binary Tree Traversal S
E
5. If a vacant left or right child area one node has then it will be used as thread. Refer to Section
Threaded Binary Tree
R

@ 8.18 POST-UNIT READING MATERIAL


T
H

zz [Link]
zz [Link]
IG

8.19 TOPICS FOR DISCUSSION FORUMS


R

zz Discuss with your friends and classmates about the concept of trees in data structure and its types.
Y

Also, discuss about the application of trees, different operations of binary tree and the difference
between complete and full binary tree.
P
O
C

28
UNIT

09

D
E
Advanced Concepts in Trees

V
R
E
Names of Sub-Units
S
E
Introduction to Advanced Trees and Application of Trees: AVL Tree, B Tree, B+ Tree, Red-Black Trees
R

Overview
T

This unit begins by discussing the concept of advanced trees. Next, the unit discusses the application
of trees. Further, the unit explains AVL trees, B tree and B+ tree. Towards the end, the unit discusses
H

the red-black trees.


IG

Learning Objectives
R

In this unit, you will learn to:


a Discuss the concept of advanced trees
Y

a Explain the importance of application of trees


P

a Describe the AVL and B tree


Explain the significance of B+ trees
O

a
a Summarise the concept of red-black trees
C

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of advanced trees
a Assess the importance of application of trees
a Evaluate the importance of AVL and B tree
a Determine the significance of B+ trees
a Explore the concept of red-black trees
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Pre-Unit Preparatory Material

a [Link]

9.1 INTrOdUCTION
Tree is one of the most significant data structures which is used for efficiently executing operations
such as insertion, deletion and searching of values. Though while working with a data of huge size, it is
not possible to create a well-balanced tree for sorting all the data. Thus, only valuable data is kept as a

D
tree and the definite size of data being used frequently changes through the insertion of new data and
deletion of current data. You will find in some cases where the NULL link to a binary tree to distinct links
is called as threads and hence it is probable to implement traversals, insertions, deletions without using

E
either stack or recursion.

V
Linked list offer higher benefits in terms of adaptability as compared to the adjacent data representation
offered by the other data structures. However, there are many drawbacks as well. The tree offers much

R
versatile data storage techniques. The worst case execution of a binary search tree is similar to the
linear search program execution, O(n). It is difficult to anticipate the pattern and its periodicity in the

E
concrete data. Hence we must balance the binary search trees.

9.2 AVL Tree S


E
In a data structure AVL tree is defined as height balanced binary search tree (BST) in which each
individual node is connected with a balance factor and the difference of height of right and left subtree
R
is less than or equal to one by deducting the height of its right from that of its left subtree. This method
of balancing in AVL tree was exposed by Adelson, Velshi and Landis provide the short name as AVL
tree or balanced binary tree. When the balance factor of each node of right and left subtree of a tree
T

is between -1 to 1, it said to be a balanced tree if not it is considered as unbalanced. The balanced and
H

unbalanced tree is shown in Figure 1:


IG

2
C

0 1
R

B B

0 0 0
Y

A C A
P

Balanced Not Balanced


O

Figure 1: Balanced and Unbalanced Tree


C

From Figure 1 considering the second tree, the height is 2, the balance factor is 2. To make the tree AVL
tree a balance factor of 1 should be maintained as:
Balance Factor = height of (left-subtree) – height of (right-subtree)
If the balance factor becomes greater than 1, the tree is stabilized through the rotation processes. For
auto balancing, an AVL tree might carry out four types of rotations are as follows:
zz Left rotation
zz Right rotation

2
UNIT 09: Advanced Concepts in Trees JGI JAINDEEMED-TO-BE UNIVERSITY

zz Left-right rotation
zz Right-left rotation

9.2.1 Left rotation


During insertion of a node in the right subtree if a an AVL tree gets unbalanced then one left rotation is
carried out as shown in Figure 2:

D
2
A A

E
1 0
B B B

V
0 0 0

R
C C A C

Right Unbalanced Tree Left Rotation Balanced

E
S
Figure 2: Left rotation
E
In the Figure 2, the tree is balanced by performing left rotation, where A becomes the left subtree of B.
R

9.2.2 right rotation


T

During the insertion of a node in the left subtree if an AVL tree gets unbalanced then a right rotation is
carried out, as shown in Figure 3:
H
IG

2
A A
R

1 0
B B B
Y

0 0 0
C C A C
P

Left Unbalanced Tree Right Rotation Balanced


O
C

Figure 3: right rotation

As shown in Figure 3 above the AVL tree is balanced by carrying out right rotation, pushing C to the
right subtree.

9.2.3 Left-right rotation


Double rotations are at intricate variants of previous kinds of rotations.

3
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

A left right rotation is a fusion of left rotation followed by right rotation, as shown in Table 1:

Table 1: Fusion of Left-right rotation

State Action
2
C

1
There was an addition of a node in the right side of the left subtree,which leaves C

D
A unstabilised. To make the AVL tree completely balance we need to perform left right
rotation.

E
0

V
B

R
C

E
Initially a left rotation is carried out on the left subtree of C, which designates A as
A
the left subtree of B.
S
E
B
R

2
C
T
H

1
B Node C is not stabilised yet, because the height of the tree is 2.
IG

0
A
R

C
Y
P

Now, a right rotation is performed on the tree, which designates B as the root and
B
makes C as the right node of the left subtree.
O

A
C

0
B

Thus, we have balanced the AVL tree.


0 0
A C

4
UNIT 09: Advanced Concepts in Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

9.2.4 right-Left rotation


This double rotation is a fusion of right rotation, followed by left rotation as shown in Table 2:

Table 2: Fusion of right-Left rotation

State Action
2
A

D
1
There was a node addition to the left of the right subtree, making A as an unstabilised
C
node with height 2.

E
0

V
B

R
A

E
C Initially a right rotation is carried out on node C, designating C as the right node of
the subtree B and making B as right Child of A.

S
E
B
R
2
A
T

1
B Node A is unsterilized as the height is 2.
H

0
C
IG

A
R

We carry out a left rotation on node B, designating B as the root and making A as
B
the left child of B.
Y
P

C
O

0
B
The given AVL tree is stabilised or balanced.
C

0 0
A C

9.3 B Tree
B tree is referred as self-balanced search tree. In order to analyse the mechanism of B trees, let us assume
was quantity of information which cannot be held in the main memory. Hence, the additional data is
stored in the disks. The data retrieval time span of disk is greater than main memory. The technique is

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

to use B trees to minimize the disk visits. Majority of the functions on trees, such as searching, insertion,
deletion, finding maximum, minimum, etc., need O(h) disk visits, where h indicates height of the tree.
The height of B-Trees is retained as minimum by keeping greatest probable keys in any node. In general
the capacity of a node in B tree is retained as identical to the capacity of the disk block. With lower
heights the maximum number of disc visits is also minimised in contrast to balanced binary search
trees such as AVL and red-black trees.
Time Complexity of B-Tree is shown in Table 3:

Table 3: Time Complexity of B Tree

D
S. No. Algorithm Time Complexity
1. Searching O(log n)

E
2. Insertion O(log n)

V
3. Deletion O(log n)

R
The following points describe the characteristics of B tree are as follows:
Entire leaf nodes share the identical level.

E
zz

zz A B tree is designated by the lowest degree’s’ whose value relies on the capacity of disk.
zz
should consist of at least 1 key. S
All the nodes excluding the root compulsorily consists of minimum (ceiling) ([t-1]/2) keys. The root
E
zz Entire nodes might consist of utmost t – 1 key.
R
zz The total count of child nodes of an individual node is identical to the sum of total keys and 1.
zz Entire set of keys are arranged in ascending order. A child node amidst of two keys Key1 & Key2
T

consists of the keys ranging from Key1 to Key2.


In contrast to the BST, B-Tree expands and contracts through the root. A BST expands bottomward
H

zz
and contracts from below as well.
IG

zz In B-trees, time complexity for searching, insertion and deletion is O(log n).
zz It is possible to add a node in B-Tree at Leaf Node alone.

Figure 4: depicts the B tree of order 5


R
Y

100
P
O

35 65 130 180
C

10 20 40 50 70 80 90 110 120 140 160 190 240 260

Figure 4: B Tree of Order 5

From the above figure it is clear that entire leaf nodes are at the identical level, entire non-leaf nodes
have occupied subtrees and with keys as total children – 1.

6
UNIT 09: Advanced Concepts in Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

Some important points about the B tree facts are as follows:


zz The lowest height of a B-Tree having n total nodes and m greatest count of child nodes which a node
can possess is: hmin = [logm (n +1)] -1.
zz The greatest height of a B-Tree having n nodes and d number of least children a non-root node
possess is: hmax = [log t n+1/2] and t = [m/2].

9.3.1 B Tree Traversal


Exploring nodes of B tree resembles the In-order traversal of Binary Tree. We initiate from the extreme

D
left child, recursively display it, then iterate the identical method for leftover child nodes and keys.
Finally recursively display the extreme right child.

E
9.3.2 Search Operation in B Tree

V
The operation of finding elements in a B Tree resembles the search process of BST. Assume that we have

R
to find the key K. Beginning from the root, we travel below recursively. If the seen non-leaf node, possess
the key, the node is retained, else, we move bottomward towards relevant child (The child preceding the

E
initial larger key) of the node. If no key is found in the leaf node, a NULL is retained.
In every individual level, the search is enhanced and if the key is not found in the ambit of parent then
S
the chances of occurrence of key becomes higher in other branch. Upon arriving at the leaf node if the
E
chosen key could not be located, then NULL is shown. An example of locating the key 120 in the B-Tree is
shown in Figure 5:
R

100
T
H

35 65 130 180
IG

10 20 40 50 70 80 90 110 120 140 160 190 240 260


R

Figure 5: Locating Key 120 in B Tree


Y

The step-by-step solution of locating key 120 in B tree start with root node as shown in Figure 6(a):
P
O

Step 1: 100
C

First, search will


35 65 starts with root 130 180
node

10 20 40 50 70 80 90 110 120 140 160 190 240 260

Figure 6(a): Start at root Node

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

After the root node we will search the range where we insert the key 120 as shown in Figure 6(b):

So, the control will


Step 2: 100 jump to this node

Then, it will check in which range


the key is i.e. as key 120 is >100 and
35 65 <130 so it has to be in left branch 130 180
of the B-Tree

D
10 20 40 50 70 80 90 110 120 140 160 190 240 260

E
Figure 6(b): Identifying the range of Key

V
After searching the range of a key in a tree it has to be in the rightmost child node of the current parent

R
as shown in Figure 6(c):

E
Step 3: 100

S
Now, as the given key 120 < 130 so
E
it has to be in the rightmost child
35 65 node of the current parent. 130 180
R

10 20 40 50 70 80 90 110 120 140 160 190 240 260


T
H

So, the control will Now, we get the key


jump to this node having value 120
IG

Figure 6(c): Getting the Key Having Value 120


In the above illustration, our scope of search was minimised by restricting ourselves to those possibilities
R

where the occurrence of the key value is supposed to be higher. If in the Figure 6(c), then we try to find
180, then the algorithm will halt because of its presence in the current node. If we try to look for 90 the
Y

program flow will be directed to the left subtree.


P

9.4 B+ TreeS
O

B+ tree augments B Tree permitting much organised data addition, removal and search functionalities.
In B Tree, both the interior and leaf nodes can hold the key values and information. Contrasting to this,
C

in B+ tree, the information is held at the leaf nodes and the key values are held in the interior nodes. In
B+ tree the leaf nodes are interconnected, establishing a singly linked list making search inquiries much
organised.
B+ tree are utilised to hold the huge quantity of information for which the main memory is insufficient,
because of the restricted storage capacity. The interior nodes (holding key values to fetch data) of the B+
tree are held in the main memory but the leaf nodes are reserved in the auxiliary memory.

8
UNIT 09: Advanced Concepts in Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

We refer the interior nodes of B+ tree as index nodes of order 3 as shown in Figure 7:

90

60 78 108 120

D
53 57 69 74 83 88 96 105 113 118 135 190

E
Figure 7: B+ Tree of Order 3

V
The following points describe the benefits of B+ tree in data structure are as follows:

R
zz Data is retrieved with equal count of disk visits.
We can always find B+ tree with balanced height in contrast to B tree.

E
zz

zz The information could be retrieved from a B+ tree serially and straight away.
zz We can make use of the Keys for cataloguing.
S
E
The comparison between B+ tree and B tree is shown in Table 4:
R
Table 4: Comparison of B + Tree with B Trees

S. No. B Tree B+ Tree


T

1. Only unique search key values are reserved. Superfluous search keys can exist.
H

2. Information is held either in leaf nodes or interior Information is held in leaf nodes.
nodes.
IG

3. Locating certain key values or information could be Rapid search results contrast to B-trees,
prolonged as data is held in the interior and leaf nodes. since information is located in leaf nodes.
4. Removal of interior nodes is complex and requires Removal of any node is simple as all the
R

larger time span. nodes are leaf nodes.


5. It is not possible to interconnect the leaf nodes. To make the search operations well organised,
Y

leaf nodes are interconnected.


P

9.5 red-BLACK TreeS


O

Red-black tree is referred to as a self-balanced tree, where the individual nodes possess an additional bit
indicating the colour – black or red. The colours are utilised for assuring that the tree is kept balanced
C

during data addition and removal. The time to search an element is O(log n), where n refers to the
overall count of data values in the tree. Rudolf Bayer devised the tree in 1972.
We must underline that every node needs single bit of memory to hold the data of colour. Such categories
of trees display alike memory traces contrast to the vintage (colorless) BST. Canons to be complied by
red-black tree are as follows:
zz All the individual nodes must possess colour either red or black.
zz The root node is certainly black.

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz We cannot have two adjoining or adjacent red nodes, which mean a red node can never possess
either a red parent or red child).
zz All the ways from an individual node (involving root nodes) to each of its successor NULL nodes have
the identical count of black nodes.

9.5.1 Importance of red-Black Tree


Majority of the binary search tree functionalities such as search, maximum, minimum, insertion,
removal require O(h) time where h indicates height of the BST. Such operations require O(n) time, in

D
case of skewed Binary tree. If it is ensured that the height of the tree is kept as O(log n) after consecutive
data addition and removal, then an upper bound of O(log n) is assured for all such functionalities. We
have O(log n) as height consistent height of red-black tree., where n stands for the count of nodes in the

E
tree. The time complexity of red-black tree is shown in Table 5:

V
Table 5: Time Complexity of red Black Tree

R
S. No. Algorithm Time Complexity
1. Searching O(log n)

E
2. Insertion O(log n)
3. Deletion
S O(log n)
E
The AVL trees are much stabilized or balanced in contrast to red-black trees, but there might be multiple
R
whirls throughout data addition and Removal. In case of our program entails recurrent data additions
and Removal, then we should favour the red black trees, whereas if instead data additions and removal
are less recurrent and data search operation is persistent, then one should favor AVL tree above red-
T

black tree.
H

9.5.2 Balancing in red Black Tree


IG

To ensure your balancing we must consider the fact that, a series of 3 nodes is impossible in the red-
black tree. One can choose any blend of colours and check whether the entire set of nodes breach the
canons of Red-Black tree. An example of red black tree where a series of 3 nodes is impossible in red-
black trees, as shown in Figure 8:
R
Y

30 30 30
P
O

20 NiL 20 NiL 20 NiL


C

10 NiL 10 NiL 10 NiL

Breaches Breaches Breaches


Property 4 Property 4 Property 3

Figure 8: red Black Tree is not Balanced

10
UNIT 09: Advanced Concepts in Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

Figure 9 shows various probable red-black trees made using above 3 keys as:

20 20

10 30 10 30

Nil Nil Nil Nil Nil Nil Nil Nil

D
Figure 9: Balancing in red-Black Tree

E
The compelling facts about Red-Black Tree are as follows:

V
zz Black height of the red-black tree refers to the count of black nodes lying on the way, from the root
of the tree to any leaf node. Leaf nodes are considered as black nodes as well. The black height of a

R
red-black tree with height h is >= h/2.
Height of a red-black tree having n nodes is given by h<= 2 log2 (n + 1).

E
z

zz Entire leaf nodes are black.


zz
S
The black depth of a node is referred as the count of black nodes encountered from the root to the
specified node, in other words the count of black progenitors.
E
zz All the red-black trees are specialised binary trees.
R
The height of any red black tree having n nodes has height <= 2Log2 (n+1). This can be verified using the
following points as:
T

zz In a common Binary Tree, if k is the least count of nodes present on all the ways from root to NULL
nodes, then n >= 2k – 1 (Eg. If k holds 3, then n is minimum 7). This can also be expressed as k <= Log2
H

(n+1).
Referring Rule 4 of Red-Black trees and above fact, it could be generalized that in a Red-Black Tree
IG

zz
having n nodes, there exists a way from root to leaf node having utmost Log2 (n+1) black nodes.
zz Referring Rule 3 of Red-Black trees,it is asserted that the count of black nodes in a Red-Black tree is
R

minimum (n/2) where n indicates the overall count of nodes.

Thus we can deduce that a red black tree having n nodes has height <= 2Log2 (n+1).
Y

Lab exercise 9a:


P

Write a C++ Program to implement an AVL Tree.


O

The following C++ program is used to implement an Avl tree is as follows:


C

// Implementation of AVL tree in C++


#include <iostream>
using namespace std;
class Node {
public:
int Key;
Node *Left;
Node *Right;

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

int height;
};
int max(int x, int y);
// Calculate height
int height(Node *N) {
if (N == NULL)
return 0;
return N->height;
}
int max(int x, int y) {

D
return (x > y) ? x : y;
}

E
// New node creation
Node *newNode(int key) {

V
Node *node = new Node();
node->Key = key;

R
node->Left = NULL;
node->Right = NULL;

E
node->height = 1;
return (node);
}
S
E
// Rotate right
Node *rightRotate(Node *y) {
R
Node *x = y->Left;
Node *T2 = x->Right;
x->Right = y;
T

y->Left = T2;
y->height = max(height(y->Left),
H

height(y->Right)) +
1;
IG

x->height = max(height(x->Left),
height(x->Right)) +
1;
R

return x;
}
Y

Node *leftRotate(Node *x) {


Node *y = x->Right;
P

Node *T2 = y->Left;


y->Left = x;
O

x->Right = T2;
x->height = max(height(x->Left),
C

height(x->Right)) +
1;
y->height = max(height(y->Left),
height(y->Right)) +
1;
return y;
}
int getBalanceFactor(Node *N) {
if (N == NULL)

12
UNIT 09: Advanced Concepts in Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

return 0;
return height(N->Left) -
height(N->Right);
}
// Inseerting a node
Node *insertNode(Node *node, int key) {
// insert a node on correct position
if (node == NULL)
return (newNode(key));
if (key < node->Key)

D
node->Left = insertNode(node->Left, key);
else if (key > node->Key)

E
node->Right = insertNode(node->Right, key);
else

V
return node;
node->height = 1 + max(height(node->Left),

R
height(node->Right));
int balanceFactor = getBalanceFactor(node);

E
if (balanceFactor > 1) {
if (key < node->Left->Key) {
return rightRotate(node);
S
E
} else if (key > node->Left->Key) {
node->Left = leftRotate(node->Left);
R
return rightRotate(node);
}
}
T

if (balanceFactor < -1) {


if (key > node->Right->Key) {
H

return leftRotate(node);
} else if (key < node->Right->Key) {
IG

node->Right = rightRotate(node->Right);
return leftRotate(node);
}
R

}
return node;
Y

}
Node *nodeWithMimumValue(Node *node) {
P

Node *current = node;


while (current->Left != NULL)
O

current = current->Left;
return current;
C

}
// delete a node from tree
Node *deleteNode(Node *root, int key) {
// Find the node and delete it
if (root == NULL)
return root;
if (key < root->Key)
root->Left = deleteNode(root->Left, key);

13
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

else if (key > root->Key)


root->Right = deleteNode(root->Right, key);
else {
if ((root->Left == NULL) ||
(root->Right == NULL)) {
Node *temperature = root->Left ? root->Left : root->Right;
if (temperature == NULL) {
temperature = root;
root = NULL;
} else

D
*root = *temperature;
free(temperature);

E
} else {
Node *temperature = nodeWithMimumValue(root->Right);

V
root->Key = temperature->Key;
root->Right = deleteNode(root->Right,

R
temperature->Key);
}

E
}
if (root == NULL)
return root;
S
E
// Balancing a tree
root->height = 1 + max(height(root->Left),
R
height(root->Right));
int balanceFactor = getBalanceFactor(root);
if (balanceFactor > 1) {
T

if (getBalanceFactor(root->Left) >= 0) {
return rightRotate(root);
H

} else {
root->Left = leftRotate(root->Left);
IG

return rightRotate(root);
}
}
R

if (balanceFactor < -1) {


if (getBalanceFactor(root->Right) <= 0) {
Y

return leftRotate(root);
} else {
P

root->Right = rightRotate(root->Right);
return leftRotate(root);
O

}
}
C

return root;
}
// Display the balanced tree
void printTree(Node *root, string indent, bool last) {
if (root != nullptr) {
cout << indent;
if (last) {
cout << “Right----”;

14
UNIT 09: Advanced Concepts in Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

indent += “ “;
} else {
cout << “Left----”;
indent += “| “;
}
cout << root->Key << endl;
printTree(root->Left, indent, false);
printTree(root->Right, indent, true);
}
}

D
int main() {
Node *root = NULL;

E
root = insertNode(root, 12);
root = insertNode(root, 30);

V
root = insertNode(root, 46);
root = insertNode(root, 67);

R
root = insertNode(root, 22);
root = insertNode(root, 65);

E
root = insertNode(root, 55);
root = insertNode(root, 7);
printTree(root, “”, true);
root = deleteNode(root, 22); S
E
cout << “After deleting “ << endl;
printTree(root, “”, true);
R
}
The output of given C++ code is as follows:
T

/tmp/QQIgPOAw1Y.o
Right----30
H

Left----12
| Left----7
IG

| Right----22
Right----65
Left----46
R

| Right----55
Right----67
Y

After deleting
Right----30
P

Left----12
| Left----7
O

Right----65
Left----46
C

| Right----55
Right----67

Lab exercise 9b:

Write a C++ Program to implement a B-Tree.


The following C++ program is used to implement a B tree is as follows:
// Searching a key on a B-tree in C++

15
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

#include <iostream>
using namespace std;
class TreeNode {
int *Keys;
int T;
TreeNode **C;
int N;
bool leaf;
public:
TreeNode(int temperature, bool bool_leaf);

D
void insertNonFull(int x);
void splitChild(int i, TreeNode *y);

E
void traverse();
TreeNode *search(int x);

V
friend class BTree;
};

R
class BTree {
TreeNode *root;

E
int t;
public:
BTree(int temp) {
S
E
root = NULL;
t = temp;
R
}
void traverse() {
if (root != NULL)
T

root->traverse();
}
H

TreeNode *search(int x) {
return (root == NULL) ? NULL : root->search(x);
IG

}
void insert(int x);
};
R

TreeNode::TreeNode(int t1, bool leaf1) {


T = t1;
Y

leaf = leaf1;
Keys = new int[2 * T - 1];
P

C = new TreeNode *[2 * T];


N = 0;
O

}
void TreeNode::traverse() {
C

int i;
for (i = 0; i < N; i++) {
if (leaf == false)
C[i]->traverse();
cout << “ “ << Keys[i];
}
if (leaf == false)
C[i]->traverse();

16
UNIT 09: Advanced Concepts in Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

}
TreeNode *TreeNode::search(int x) {
int i = 0;
while (i < N && x > Keys[i])
i++;
if (Keys[i] == x)
return this;
if (leaf == true)
return NULL;
return C[i]->search(x);

D
}
void BTree::insert(int x) {

E
if (root == NULL) {
root = new TreeNode(t, true);

V
root->Keys[0] = x;
root->N = 1;

R
} else {
if (root->N == 2 * t - 1) {

E
TreeNode *s = new TreeNode(t, false);
s->C[0] = root;
s->splitChild(0, root);
S
E
int i = 0;
if (s->Keys[0] < x)
R
i++;
s->C[i]->insertNonFull(x);
root = s;
T

} else
root->insertNonFull(x);
H

}
}
IG

void TreeNode::insertNonFull(int x) {
int i = N - 1;
if (leaf == true) {
R

while (i >= 0 && Keys[i] > x) {


Keys[i + 1] = Keys[i];
Y

i--;
}
P

Keys[i + 1] = x;
N = N + 1;
O

} else {
while (i >= 0 && Keys[i] > x)
C

i--;
if (C[i + 1]->N == 2 * T - 1) {
splitChild(i + 1, C[i + 1]);
if (Keys[i + 1] < x)
i++;
}
C[i + 1]->insertNonFull(x);
}

17
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

}
void TreeNode::splitChild(int i, TreeNode *y) {
TreeNode *z = new TreeNode(y->T, y->leaf);
z->N = T - 1;
for (int j = 0; j < T - 1; j++)
z->Keys[j] = y->Keys[j + T];
if (y->leaf == false) {
for (int j = 0; j < T; j++)
z->C[j] = y->C[j + T];
}

D
y->N = T - 1;
for (int j = N; j >= i + 1; j--)

E
C[j + 1] = C[j];
C[i + 1] = z;

V
for (int j = N - 1; j >= i; j--)
Keys[j + 1] = Keys[j];

R
Keys[i] = y->Keys[T - 1];
N = N + 1;

E
}
int main() {
BTree T(12);
S
E
[Link](23);
[Link](56);
R
[Link](44);
[Link](61);
[Link](80);
T

[Link](76);
[Link](89);
H

[Link](49);
[Link](87);
IG

[Link](54);
cout << “The B-tree is: “;
[Link]();
R

int x = 76;
([Link](x) != NULL) ? cout << endl
Y

<< x << “ is found”


: cout << endl
P

<< x << “ is not Found”;


x = 49;
O

([Link](x) != NULL) ? cout << endl


<< x << “ is found”
C

: cout << endl


<< x << “ is not Found\n”;
}
The output of given C++ code is as follows:
/tmp/QQIgPOAw1Y.o
The B-tree is: 23 44 49 54 56 61 76 80 87 89
76 is found
49 is found

18
UNIT 09: Advanced Concepts in Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

Conclusion 9.6 CONCLUSION

zz Tree is one of the most significant data structures which is used for efficiently executing operations.
zz AVL tree is defined as height balanced binary search tree (BST) in which each individual node is
connected with a balance factor.
zz The worst case execution of a binary search tree is similar to the linear search program execution,
O(n).
AVL tree was exposed by Adelson, Velshi and Landis provides the short name as AVL tree or balanced

D
zz
binary tree.

E
zz B tree is referred as self-balanced search tree.
zz The operation of finding elements in a B Tree resembles the search process of BST.

V
zz B+ Tree are utilised to hold the huge quantity of information for which the main memory is
insufficient.

R
zz Red black tree is referred to as a self-balanced tree, where the individual nodes possess the colour -

E
black or red.

9.7 GLOSSAry S
E
zz Tree: It is one of the most significant data structures which is used executing operations.
R
zz AVL trees: It is a special binary search tree which auto balances it.
zz B trees: It is a special tree which auto stabilizes itself-preserves the arranged information.
T

zz B+ trees: It is a tree having a variable with greater count of children for every node.
H

zz red black tree: It is referred to as a self-balanced tree, where the each node has black or red colour.
IG

9.8 SeLF-ASSeSSMeNT QUeSTIONS


R

A. Multiple Choice Questions


1. __________ is one of the most significant data structures which are used for efficiently executing
Y

operations such as insertion, deletion and so on.


P

a. Tree
b. Avl tree
O

c. Binary tree
C

d. B+ tree
2. During insertion of a node in the right subtree if an AVL tree gets unbalanced then one __________
is carried out.
a. Right rotation
b. Left rotation
c. Left-right rotation

19
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

d. Right-left rotation
3. Which among the following is the time complexity of B tree for searching?
a. O(log n+1)
b. O(log n-1)
c. O(log n)
d. log n
4. The operation of finding elements in a B Tree resembles the __________ process of BST.

D
a. Insertion
b. Deletion

E
c. Rotation

V
d. Searching
5. It is possible to add a node in B-Tree at __________ alone.

R
a. Child node

E
b. Leaf node
c. Parent node
d. Root node S
E
6. For auto balancing, an AVL tree might carry out __________ types of rotations.
R
a. 1
b. 2
T

c. 3
H

d. 4
7. The worst case execution of a binary search tree is similar to the linear search program execution is:
IG

a. O(log n+1)
b. O(log n)
R

c. O(n)
d. O(log n-1)
Y

8. When the balancing factor becomes greater than 1, the tree is stabilised through which process?
P

a. Rotation
O

b. Insertion
c. Searching
C

d. Deletion
9. Which among the following tree is utilised to hold the huge quantity of information for which the
main memory is insufficient, because of the restricted storage capacity?
a. Binary tree
b. Avl tree
c. Threaded tree

20
UNIT 09: Advanced Concepts in Trees JGI JAIN
DEEMED-TO-BE UNIVERSITY

d. B+ tree
10. Red black tree is referred to as a self-balanced tree, where the individual nodes possess an additional
bit indicating the colour - black or red was discovered in __________.
a. 1972
b. 1974
c. 1977
d. 1983

D
B. essay Type Questions
1. You will find in some cases where the NULL link to a binary tree to distinct links is called as threads.

E
What is the concept of trees in data structure?

V
2. The method of balancing in AVL tree was exposed by Adelson, Velshi and Landis provide the short
name as AVL tree or balanced binary tree. Describe AVL tree in brief.

R
3. The data retrieval time span of disk is greater than main memory. The technique is to use B trees to
minimize the disk visits. Describe the importance of B tree in data structure.

E
4. In B+ tree, the information is held at the leaf nodes and the key values are held in the interior nodes.
Explain the significance of B+ tree in data structure.
S
5. We must underline that every node needs single bit of memory to hold the data of colour. Determine
E
the concept of colours of red black tree and how its colour makes it different from other trees.
R

9.9 ANSwerS ANd HINTS FOr SeLF-ASSeSSMeNT QUeSTIONS


T
H

A. Answers to Multiple Choice Questions


IG

Q. No. Answer
1. a. Tree
2. b. Left rotation
R

3. c. O(log n)
Y

4. d. Searching
5. b. Leaf node
P

6. d. 4
O

7. c. O(n)
8. a. Rotation
C

9. d. B+ tree
10. a. 1972

B. Hints for essay Type Questions


1. Tree is one of the most significant data structures which is used for efficiently executing operations
such as insertion, deletion and searching of values. Refer to Section Introduction

21
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

2. In a data structure AVL tree is defined as height balanced binary search tree (BST) in which each
individual node is connected with a balance factor. Refer to Section AVL Tree
3. B tree is referred as self-balanced search tree. In order to analyse the mechanism of B trees, let us
assume was quantity of information which cannot be held in the main memory. Refer to Section B
Tree
4. B+ Tree augments B Tree permitting much organised data addition, removal and search
functionalities. In B Tree, both the interior and leaf nodes can hold the key values and information.
Refer to Section B+ Tree

D
5. Red black tree is referred to as a self-balanced tree, where the individual nodes possess an additional
bit indicating the colour - black or red. Refer to Section Red Black Tree

E
@ 9.10 POST-UNIT reAdING MATerIAL

V
[Link]

R
zz

zz [Link]

E
9.11 TOPICS FOr dISCUSSION FOrUMS
S
E
zz Discuss the concept of advanced trees in data structure and its importance with your friends and
R
classmates. Also, discuss the various trees, such as AVL tree, B tree and B+ tree, with examples.
T
H
IG
R
Y
P
O
C

22
UNIT

10

D
Advanced and

E
Complex Data Structures

V
R
E
Names of Sub-Units
S
E
Introduction to Advanced and Complex Data Structures, Disjoint Sets, Self-Balancing Trees, Segment
R
Trees, Tries, Suffix Array and Tree
T

Overview
H

This unit begins by discussing the concept of advanced and complex data structures. Next, the unit
discusses the disjoint sets and self-balancing trees. Further, the unit explains the segment tress and
IG

tries. Towards the end, the unit discusses the suffix array and tree.
R

Learning Objectives
Y

In this unit, you will learn to:


Discuss the concept of advanced and complex data structures
P

a Explain the concept of disjoint sets


O

a Describe the importance of self-balancing trees and segment trees


Explain the significance of tries
C

a Discuss the concept of suffix array and tree


JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of advanced and complex data structures

a Assess the concept of disjoint sets


a Evaluate the importance of self-balancing trees and segment trees
a Determine the significance of tries

D
a Explore the concept of suffix array and tree

E
Pre-Unit Preparatory Material

V
a [Link]

R
analysis-of-algorithms-spring-2012/lecture-notes/MIT6_046JS12_lec16.pdf

E
10.1 INTrODUCTION

S
Complex data structures persist as one of the indispensable offshoot of data science which is used for
vault, logistics and governance of data and information for efficient, easy accessibility and modification
E
of data. They act as the fundamental component for generating coherent and constructive software
design and algorithms. The awareness of building and devising a sterling data structure is crucial for
R
being a creditable programmer. Its purview is expanding with the advent of innovative approaches of
execution in information technology.
T

10.2 DISjOINT SeTS


H

The productivity of an algorithm occasionally relies on underlying data structure. An eminent data
structure, say for example, disjoint-set-union, minimises the running timespan of an algorithm.
IG

Imagine that, you operate on a group of N elements that are divided in different subsets where it is
required chase the correlation among items of a particular subset or correlation among the subsets.
R

One can utilise the union-find algorithm (disjoint set union) to attain this.
Assume 5 persons, Q, R, S, and T
Y

P is Q’s chum, Q is R’s chum, S and E are bezzies, hence, the facts presented below are correct are as
P

follows:
O

zz P, Q, and R are associated.


zz S and T are interlinked as well.
C

We can utilise the union-find data structure to verify the associativity among individual friends either
straight away obliquely. We can be assuring of the dual distinct detached subsets, in this case. The dual
distinct subsets are {A, B, C} and {D, E}.
We need to carry out dual operations are as follows:
zz Union(P, Q): Link the items P and Q
zz Find(P, Q): search if the items P and Q are interlinked.

2
UNIT 10: Advanced and Complex Data Structures JGI JAINDEEMED-TO-BE UNIVERSITY

For instance, consider a group of items A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. Since ten data items are present,
(N = 10).
P and Q data items are interlinked only if arr[ P ] = arr[ Q ].

10.2.1 Implementation of Disjoint Sets


For performing the union and find processes, the steps mentioned below are to be carried out:
zz Find(P, Q): Verify if arr[ P ] = arr[ Q ]

D
zz Union(P, Q): link P to Q and combine the constituents which includes P and Q by restoring items
present in arr[ P ] with the value in arr[ Q ].

E
In the beginning, we have 10 subsets and individual subsets has single data item as shown in Figure 1 (a):

V
R
0 1 2 3 4 5 6 7 8 9

E
S
Figure 1(a): 10 Subsets of Single Data
E
The corresponding array of 10 subsets as shown in Figure 1(b):
R

Arr 0 1 2 3 4 5 6 7 8 9
T

0 1 2 3 4 5 6 7 8 9
H
IG

Let us carry out few operations as shown in Figure 1(c):


R

0 1 3 4 5 6 7 8 9
Y

2
P
O
C

The respective array is shown in Figure 1(d):

Arr 0 1 1 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The union of (4,3), (8,4) and (9,3) is shown in Figure 1(e):

0 1 3 5 6 7

2 9 4

D
E
The corresponding array elements are shown in Figure 1 (f):

V
Arr 0 1 1 3 3 5 6 7 3 3

R
0 1 2 3 4 5 6 7 8 9

E
The union of (6,5) is shown in Figure 2(g):
S
E
0 1 3 5 7
R

2 9 4 6
T
H

8
IG

The corresponding elements are shown in Figure 1 (h):


R

Arr 0 1 1 3 3 5 5 7 3 3
Y

0 1 2 3 4 5 6 7 8 9
P

Post execution of Union (P, Q), we have 5 subsets:


O

zz Subset1 has the data items {3, 4, 8, 9}


Subset 2 has the data items {1, 2}
C

zz

zz Subset3 has the data items {5, 6}


zz Subset4 has the data items{0}
zz Subset6 has the data items {7}

The constituents of a subset, interlinked with one another either straight away obliquely, could be viewed
as the vertices or nodes of specific graph. Hence, such formulated subsets are known as connected
components.

4
UNIT 10: Advanced and Complex Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

In graphs, the union-find data structure is used to perform many tasks such as interconnecting nodes,
searching connected components, and so on.
Let’s carry out few find (P, Q) operations:
zz Find (0, 7): 0 and 7 are detached, hence, false will be displayed as output.
zz Find (8, 9): since 8 and 9 are interlinked obliquely, the output will display true value.

There are multiple approaches to achieve this. But the ideal is weighted union operation as described
below:

D
zz We have to keep a record of capacity of all subsets and during interlinking two constituents link
the root of the subsets which possess minimal count of data items to the root of the subsets which
possess a greater count of data items.

E
zz If we wish to link 1 and 5, then interlink the root of subset A (the subset comprising 1) with the root

V
of subset B ( the subset comprising 5) as subset. A consists of minimal count of data items when
compared to subset B as shown in Figure 2:

R
E
root root
6 6

3
root

7 5
S 3 7 5
E
R

1 2 9 4 10 1 1 1 1 1
T

Figure 2: Subset A contain minimal data items then Subset B


H

The process mentioned above will poise the tree created by carrying out the operations explained priory.
IG

The process is termed as weighted-union operation.


To begin with, the capacity of individual subset is 1 as individual subsets consist of single data item. You
can set it in the initialize function mentioned below. The capacity [ ] array will record of the capacity of
R

individual subsets.
Y

The following algorithm is to initialize the union functions are as follows:


//updated initialize procedure:
P

void initialize( int Arr[ ], int N)


O

{
for(int count = 0;count<N;count++)
{
C

Arr[ count ] = i ;
capacity[ count ] = 1;
}
}
We have to update the union function since the dual subsets will be interlinked depending upon count of
data items in individual subsets.

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The following algorithm is to update the union functions are as follows:


//Updated union function
void weighted-union(int Arr[ ],int capacity[ ],int P,int Q)
{
int root_P = root(P);
int root_Q = root(Q);
if(capacity[root_P] < capacity[root_Q ])
{
Arr[ root_P ] = Arr[root_Q];

D
capacity[root_Q] += capacity[root_P];
}
else

E
{

V
Arr[ root_Q ] = Arr[root_P];
capacity[root_P] += capacity[root_Q];

R
}
}

E
10.3 SeLF-BALANCINg TreeS

S
Self-Balancing BSTs are height-balanced binary search trees that maintain height on their own.
as minimal during data addition and removal processes carried out on tree. The height is preserved
E
approximately as Log n for executing operations in time span of O(Log n) on the whole.
R

10.3.1 red Black Tree


Red black tree is referred to as a self-balanced tree, where the individual nodes possess an additional bit
T

indicating the colour -black or red. The colours are utilised for assuring that the tree is kept balanced
H

during data addition and removal. The time to search an element is O(log n), where n refers to the
overall count of data values in the tree. Rudolf Bayer devised the tree in 1972.
IG

We must underline that every node needs single bit of memory to hold the data of colour. Such categories
of trees display alike memory traces contrast to the vintage (colourless) BST.
Canons to be complied by Red-Black tree are as follows:
R

zz All the individual nodes must possess colour either red or black.
Y

zz The root node is certainly black.


P

zz We cannot have two adjoining or adjacent red nodes, which mean a red node can never possess
either a red parent or red child).
O

zz All the ways from an individual node (involving root nodes) to each of its successor NULL nodes have
the identical count of black nodes.
C

10.3.2 AVL Tree


In a data structure AVL tree is defined as height balanced binary search tree (BST) in which each
individual node is connected with a balance factor and the difference of height of right and left subtree
is less than or equal to one by deducting the height of its right from that of its left subtree. This method
of balancing in AVL tree was exposed by Adelson, Velshi, and Landis provide the short name as AVL

6
UNIT 10: Advanced and Complex Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

tree or balanced binary tree. When the balance factor of each node of right and left subtree of a tree is
between -1 to 1, it said to be a balanced tree if not it is considered as unbalanced.
The balanced and unbalanced tree is shown in Figure 3:

2
C

0 1
B B

D
0 0 0

E
A C A

V
Balance Not Balance

R
Figure 3: Balanced and Unbalanced Tree

E
From the figure 3, considering the second tree, the height is 2, the balance factor is 2. To make the tree
AVL tree a balance factor of 1 should be maintained as:
S
Balance Factor = Height of (left-subtree) – Height of (right-subtree)
E
If the balance factor becomes greater than 1, the tree is stabilized through the rotation processes. For
R
auto balancing, an AVL tree might carry out four types of rotations are as follows:
zz Left rotation
T

zz Right rotation
Left-Right rotation
H

zz

zz Right-Left rotation
IG

10.3.3 Usage of Self Balancing Tree in Programming Languages


Presence of set and map options in the Standard Template Library (STL) in C++. We have Tree Set and
R

Treemap options in Java. Majority of the data structures to implement library functionality utilise Red
Black Tree. One can utilise the Python modules such as Pypi,rbtree and pyavl implement the red black
Y

tree and AVL trees.


P

The time complexity of self-balancing trees are shown in Table 1:


O

Table 1: Time Complexity of Self-Balancing Trees

Criteria rB Tree AVL Tree Splay Tree


C

Data addition in worst O(1) O(logn) Amortized O(logn)


case
Greatest height of tree 2*log(n) 1.44*log(n) O(n)
Locating elements in O(logn), O(logn), Amortized O(logn),
worst case Modest Rapid Lower

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Criteria rB Tree AVL Tree Splay Tree


Productive Three pointers having Two pointers having Possess dual pointers lacking
performance needs colour bits for individual balance factor for additional data.
nodes. individual node
Removal in worst case O(logn) O(logn) Amortised O(logn)
Widely utilised As ubiquitous data When recurrent data When identical data item is
structure quest are needed. accessed multiple times
Concrete application Database transactions Multiset, multimap, map, Implementing cache, garbage

D
set, etc. collection algorithms

E
10.4 SegMeNT TreeS

V
It is, in essence, a binary tree. A segment tree is a binary tree that is used to store intervals or segments.
In the segment tree, each node represents an interval.

R
We make use of the segment trees in situations which involves various range queries on arrays,and
updations of data items of array. For instance, calculating the sum of all data items in an array ranging

E
with indices denoting intervals(L) to (R), lying in between 0 to N-1, in the range of searching the lowest
(popularly addressed as Range Minimum Query nodus) of entire data items of an array with indices
S
ranging from L to R. Such problems can be comfortably resolved through one among the adaptable
data structures, segment tree.
E
R
10.4.1 Visualisation of Segment Trees
We can view the Segment Trees primarily as a binary tree utilised for holding the intervals or segments.
T

The individual nodes of the Segment Tree denote an interval. Assume an array P with capacity N and
the respective Segment Tree as T:
H

zz Root node of T indicates the entire array P[0:N−1].


The leaves of T indicates a solitary data item P[i] such that 0≤i<N.
IG

zz

zz The interior nodes of T indicates the union of rudimentary intervals A[i:j] where 0≤i<j<N.

Entire array P [0:N−1] is denoted as root of segment tree. it is split in two semi segments which acts as
R

descendants of the root denoted by P[0:(N−1)/2] and P[(N−1)/2+1:(N−1)]. Height of the segment tree is
given by log2N. The N leaves denote the N data items of the array. The count of interior nodes is N−1. The
Y

overall count of nodes is calculated as 2×N−1.


P

The following functionalities are offered by segment trees:


O

zz Update: To modify the data item of the array P and display the respective updates in the segment
tree.
C

zz Query: This is utilized to query an interval and retain the solution of a problem.

10.4.2 Implementation of Segment Tree


A Segment Tree is represented through, a linear array and created by making use of recursion (following
a bottom-up mechanism). Begin with the leaf nodes, move towards the root and modify the nodes lying
in the way from leaf nodes to root. Leaf nodes denote a solitary data item. At every stage, the values of
two descendants are utilised to create an interior antecedent node. The interior nodes denote union or

8
UNIT 10: Advanced and Complex Data Structures JGI JAINDEEMED-TO-BE UNIVERSITY

merge of segments of descendants. For update(), find the leaf nodes which consists of the data item to
be modified, which is achieved by moving towards either the left descendant or the right descendant,
based on the segment consisting the data item. When the leaf is located, it is modified and using the
bottom-up mechanism the modifications are made in the way from that leaf node to the root.
To query() a Segment Tree, choose a range from L to R (present in the question). Perform recursion on
the tree initiating with the root and verify whether the segment denoted by the node lies in the range of
L to R. In case it falls in the range, retain the value of the node.
The corresponding Segment Tree for array A with capacity 7 resembles as per Figure 4:

D
1 A[0:6]

E
V
2 A[0:3] 3 A[4:6]

R
4 A[0:1] 5 A[2:3] 6 A[4:5] 7 A[6:6]

E
A[0:0] 9 A[1:1] 10 A [ 2 : 2 ] 11 A [ 3 : 3 ] 12 A [ 4 : 4 ] 13 A [ 5 : 5 ]

S
E
Figure 4: Segment Tree
R
Figure 5 depicts the segment tree represented as a linear array as per above figure:

tree [ 1 ] = A [ 0 : 6 ]
T

tree [ 2 ] = A [ 0 : 3 ]
tree [ 3 ] = A [ 4 : 6 ]
H

tree [ 4 ] = A [ 0 : 1 ]
tree [ 5 ] = A [ 2 : 3 ]
tree [ 6 ] = A [ 4 : 5 ]
IG

tree [ 7 ] = A [ 6 : 6 ]
tree [ 8 ] = A [ 0 : 0 ]
tree [ 9 ] = A [ 1 : 1 ]
tree [ 10 ] = A [ 2 : 2 ]
R

tree [ 11 ] = A [ 3 : 3 ]
tree [ 12 ] = A [ 4 : 4 ]
tree [ 13 ] = A [ 5 : 5 ]
Y
P

Figure 5: Segment Tree represented as Linear Array


Consider an array A with capacity N and few queries. The queries are divided in two classes:
O

zz Update: provided index and val, modify array item A[index] as A[index]=A[index]+val.
C

zz Query: provided l and r retain the value of A[l]+A[l+1]+A[l+2]+…..+A[r−1]+A[r] such that 0≤l≤r<N

We can have different orders for Queries and Updates are as follows:
zz Naive Algorithm: This is the most fundamental method. Run a loop from l to r and calculate the
total of all the elements for the query. As a result, the query will take O. (N). The value of the element
will be updated if A[idx] += val is used. It will take O to complete the update (1). This technique works
well when there are a lot of update actions and few query operations.

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz Another Naive Algorithm: In this approach, the cumulative total of the array’s elements is pre-
processed and stored in an array sum. Simply return for each query (sum[r] - sum[l-1]). The query
operation will now take O minutes (1). To update, however, we must execute a loop and alter the
value of the entire sum[i] so that l = I = r. As a result, the update operation will take O. (N). This
technique works well when there are a lot of query operations and few update operations.
zz Utilising segment tree: In this problem, we’ll see how to use segment trees and what we’ll store in
them. Each node of the segment tree will represent an interval or segment, as we know. We must
find the sum of all the elements in the provided range in this problem. As a result, the total of all
the elements of the interval represented by the node will be stored in each node. How do we go

D
about doing that? As previously stated, we will construct a segment tree using recursion (bottom-up
approach). A single element will be present on each leaf. The total of both children will be present in

E
all internal nodes.
void create(int node, int begin, int last)

V
{
if(begin == last)

R
{
// Leaf node possesses single data item

E
tree[node] = A[begin];
}
else
S
E
{
int mdl = (begin + last) / 2;
R
// apply recursion on the left child
create(2*node, begin, mdl);
// apply recursion on the right child
T

create(2*node+1, mdl+1, last);


// Interior node possess the sum of its child nodes.
H

tree[node] = tree[2*node] + tree[2*node+1];


}
IG

}
Here 2 × node indicates the left node and 2×node+1 indicates the right node, begin and last indicates
the interval denoted by the node. Complexity of create() is O(N). Figure 6 depicts segment tree of A
R

(1,3,5,7,9,11):
Y

A[0:5] 36
P
O

A[0:2] 9 27 A[3:5]
C

A[0:1] 4 5 16 A[3:4] 11

1 3 7 9

Figure 6: Segment Tree of A (1,3,5,7,9,11):

10
UNIT 10: Advanced and Complex Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

The time Complexity of update operation is O(logN).


To query a provided range, verify 3 criterias:
1. Range denoted by a node lies within the provided range
2. Range denoted by a node lies external to the provided range
3. A node’s range is partially inside and partly outside of the supplied range.

Time Complexity of query is O(logN). The following algorithm describe the time complexity of query is
O(logN) are as follows:

D
int query(int node, int begin, int last, int l, int r)
{

E
if(r < begin or last < l)
{

V
// range denoted by a node is entirely external to the provided range
return 0;

R
}
if(l <= begin and last <= r)

E
{

S
// range denoted by a node is entirely within the provided range
return tree[node];
E
}
// range denoted by a node is partly interior and partly exterior to the
R
provided range
int mdl = (begin + last) / 2;
int q1 = query(2*node, begin, mdl, l, r);
T

int q2 = query(2*node+1, mdl+1, last, l, r);


H

return (q1 + q2);


}
IG

10.5 TrIeS
The word “Trie” is an abbreviation for “retrieval.” The set of strings is stored in a sorted tree-based data
R

structure called a trie. Each node has the same number of pointers as the number of characters in the
alphabet. It may use the prefix of a word to look up that word in the dictionary. If we suppose that all
Y

strings are made up of the letters a through z from the English alphabet, each trie node can have a
maximum of 26 points.
P

Tries are exceptional data-structures dependent on the prefix of a string. They denote the access to
O

information and are termed as Trie.


We can reckon strings as a significant and general theme of multiple of programming snags. Processing
C

strings has multiple of concrete applications, some are displayed below:


zz Search Engines
zz Genome Analysis
zz Data Analytics
Entire textual data accessible to us can be interpreted as strings.

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

10.5.1 Prefix of String


The prefix of a string S represents the initial n letters n≤|S| from which the given string commences. For
instance, the word “abacaba” possess the prefixes mentioned below:
a
ab
aba
abac
abaca
abacab

D
Trie refers to a remarkable data structure utilised to reserve strings which could be viewed as nodes
of graph. Every node contains of atmost 26 successors and edges link each antecedent node to its

E
descendants. The 26 child nodes represent the 26 letters of the English alphabet series.

V
Strings are held in a top down approach on the based on the prefixes of a Trie. Entire prefixes having
size 1 are reserved till level 1, the prefixes having size 2 are reserved till level 2 and Sequence continues.

R
For instance, as shown in Figure 7:

E
NULL

S
E
a b a b
a b a
R
a b c
a d
b d a b a
b a d
T

b a g
H

a b d g
IG

Figure 7: Prefix of String

Now, it is obvious to wonder why we prefer a Trie for working with a single string. In general, Tries are
R

applicable on cluster of strings, instead of a solo string. With various strings, we could resolve a multiple
problems relying on them. For instance, let us think of an English dictionary and a solo strings, search
Y

the prefix of greatest size from the dictionary coinciding with string involving tries could resolve this
problem in a more organised way.
P

A Trie consists of 26 outgoing edges representing the individual letters of the alphabet.
O

The pseudo code for adding a string into a Trie is as follows:


void insert(String s)
C

{
for(each char in string s)
{
if(successor of the current char is null)
{
child node=new Node();
}
current_node=child_node;

12
UNIT 10: Advanced and Complex Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

}
}
The pseudo code for verifying whether a specific word is present in a dictionary or not is as follows:
boolean Verify(String s)
{
for(every char in String s)
{
if(successor is null)
{

D
return false;
}

E
}
return true;

V
}

R
10.6 SUFFIx ArrAyS AND TreeS
A suffix array is an organized collection of all the suffixes in a string. The description is alike to that of

E
the Suffix Tree, which is a compressed trie of all suffixes in a text. Any suffix tree-based technique can be
substituted with a suffix array enriched with additional information that solves the similar problem in
the same amount of time (Source Wiki). S
E
By performing a DFS traverse of the suffix tree, a suffix array can be generated. In fact, both the suffix
array and the suffix tree can be built in linear time from each other.
R

Suffix array refers to the structure based upon arrays. It is a lexical arranged array holding suffixes of
a string s. Consider the string s = abakan, which has six suffixes: abakan, bakan, akan, kan, an, n, and
T

the related suffix tree as shown in Figure 8:


H

0 : abakan
1 : akan
IG

2 : an
3 : bakan
4 : kan
R

5:n
Y

Figure 8: 6 suffix of word abakan


P

For minimising the memory space, we do not reserve the suffixes explicitly. It is adequate to reserve
their indices alone.
O

Suffix arrays, integrated with LCP table (indicates longest common prefix of neighbouring suffixes
table), are extremely worthy for resolving multiple problems. Suffix arrays are created in O(n * log2n)
C

time, where n indicates the length of s. The time complexity could be enhanced to O(n * log n) through
linear time sorting algorithm.

Correlation among suffix tree and suffix array:


It is noteworthy to put forth, that it is possible to build Suffix Array straight away through a suffix tree
in linear time by making use of DFS traversal.

13
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

We view suffix tree as a natural refinement over Tries utilised in pattern recognition cases. Such Tries
consists of Iengthier ways excluding branches. If we minimise such lengthy pathways in single leap, the
length of Trie shrinks considerably. Such a contracted trie described on the A suffix tree of s is a subset
of a string’s suffixes.
Take, for example, the suffix tree for the string s = abakan. The word possess 6 suffixes {abakan , bakan,
akan, kan, an, n} and corresponding videos suffix tree resembles as shown in Figure 9:

D
a

E
a
n kan
bakan bakan

V
kan

abakan akan an bakan kan n

R
Figure 9: Suffix tree of a String S

E
Suffix trees are used to resolve various intricate problems, as it consists of detailed data regarding the
S
string. A popular application is searching the count of discrete substrings of s, which is comfortably
E
resolved through suffix tree.
R
Conclusion 10.7 CONCLUSION
T

zz Complex data structures persist as one of the indispensable offshoot of data science which is used
for vault, logistics and governance of data.
H

zz Self-balancing BSTs are height-balanced binary search trees that maintain height on their own.
Red black tree is referred to as a self-balanced tree, where the individual nodes possess an additional
IG

zz
bit indicating the colour -black or red.
zz In a data structure AVL tree is defined as height balanced binary search tree (BST) in which each
individual node is connected with a balance factor.
R

zz It is, in essence, a binary tree. A segment tree is a binary tree that is used to store intervals or
Y

segments.
A Segment Tree is represented through, a linear array and created by making use of recursion.
P

zz

zz The set of strings is stored in a sorted tree-based data structure called a trie.
O

zz A suffix array is an organized collection of all the suffixes in a string.


Suffix trees are used to resolve various intricate problems, as it consists of detailed data regarding
C

zz
the string.

10.8 gLOSSAry

zz Disjoint sets: It refers to a data structure which records a group of data items divided into a multiple
disjoint (non-imbricating) subsets, which is utilised for estimating whether two constituents belong
to the identical subset

14
UNIT 10: Advanced and Complex Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Self balancing trees: Refers to a BST which tries to maintain its height, or the count of levels of
nodes underneath the root, as minimal every time, in an automated way
zz Tries: data structure utilized for holding strings which is viewed as a graph. It contains nodes and
edges
zz red black tree: It is referred to as a self-balanced tree, where the individual nodes possess an
additional bit indicating the colour-black or red
zz AVL tree: It is defined as height balanced binary search tree (BST) in which each individual node is
connected with a balance factor

D
zz Segment tree: It is a binary tree that is used to store intervals or segments
Trie: It is the set of strings is stored in a sorted tree-based data structure called a trie

E
zz

zz Suffix array: It is an organised collection of all the suffixes in a string

V
zz Suffix trees: It is used to resolve various intricate problems, as it consists of detailed data regarding
the string

R
E
10.9 SeLF ASSeSSMeNT QUeSTIONS

1. Which among the following is the alternative name of Trie? S


E
a. Digital tree
R
b. Treap
c. Binomial tree
d. AVL tree
T

2. __________ are height-balanced binary search trees that maintain height on their own.
H

a. Disjoint set
IG

b. AVL tree
c. Red-black tree
d. Self-balancing tree
R

3. Which of these refers to the structure based upon arrays?


Y

a. Suffix trees
b. Suffix array
P

c. Segment tree
O

d. String
4. The set of strings is stored in a sorted tree-based data structure called:
C

a. Segment trees
b. Arrays
c. Tries
d. String

15
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

5. An AVL tree might carry out __________ types of rotations.


a. 1
b. 2
c. 3
d. 4
6. Which among the following provided index and val, modify array item?
a. Update

D
b. Query
c. Naïve algorithm

E
d. Arrays

V
7. The balance factor of each node of right and left subtree of a tree is between __________ then it said
to be a balanced tree if not it is considered as unbalanced.

R
a. 0 to 1

E
b. 1 to 0
c. -1 to 1
d. 1 to -1 S
E
8. Which among the following are held in a top down approach on the based on the prefixes of a Trie?
R
a. Arrays
b. String
T

c. Trees
d. Algorithm
H

9. Which of these are used to resolve various intricate problems, as it consists of detailed data regarding
IG

the string?
a. Suffix array
b. Suffix tree
R

c. Disjoint set
Y

d. Self-balanced tree
10. LCP stands for:
P

a. Longest Common Prefix


O

b. Largest Common Prefix


c. Long Common Prefix
C

d. Longest Close Prefix

B. Answers to essay Type Questions


1. The awareness of building and devising a sterling data structure is crucial for being a creditable
programmer. What is the concept of complex data structure?
2. Explain the concept of disjoint sets.

16
UNIT 10: Advanced and Complex Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY

3. The colours are utilised for assuring that the tree is kept balanced during data addition and removal.
Describe the colors concept of red-black tree.
4. A Segment Tree is represented through, a linear array and created by making use of recursion
(following a bottom-up mechanism). What is a segment tree?
5. Tries are exceptional data-structures dependent on the prefix of a string. Describe the significance
of tries.

10.10 ANSwerS AND HINTS FOr SeLF ASSeSSMeNT QUeSTIONS

D
E
A. Answers to Multiple Choice Questions

V
Q. No. Answer

R
1. a. Digital tree
2. d. Self-balancing tree

E
3. b. Suffix array
4. c. Tries S
E
5. d. 4
R
6. a. Update
7. c. -1 to 1
T

8. b. String
H

9. b. Suffix tree
10. a. Longest Common Prefix
IG

B. Hints for essay Type Questions


1. Complex data structures persist as one of the indispensable offshoot of data science which is used
R

for vault, logistics and governance of data and information for efficient, easy accessibility and
modification of data. Refer to Section Introduction
Y

2. The productivity of an algorithm occasionally relies on underlying data structure. An eminent data
P

structure, say for example, disjoint-set-union, minimises the running timespan of an algorithm.
Refer to Section Disjoint Sets
O

3. Red black tree is referred to as a self-balanced tree, where the individual nodes possess an additional
bit indicating the colour -black or red. Refer to Section Self-Balancing Trees
C

4. It is, in essence, a binary tree. A segment tree is a binary tree that is used to store intervals or
segments. In the segment tree, each node represents an interval. Refer to Section Segment Trees
5. The word “Trie” is an abbreviation for “retrieval.” The set of strings is stored in a sorted tree-based
data structure called a trie. Refer to Section Tries

17
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

@ 10.11 POST-UNIT reADINg MATerIAL

z [Link]
zz [Link]

10.12 TOPICS FOr DISCUSSION FOrUMS

D
zz Discuss with your friends and classmates the concept of advanced and complexed data structure.
Also, discuss on the self-balancing trees and practice the various programming codes and assess

E
their behaviours.

V
R
E
S
E
R
T
H
IG
R
Y
P
O
C

18
UNIT

11

D
E
Heaps

V
R
E
Names of Sub-Units
S
E
Applications of Heap, Definitions of Max-Heaps and Min-Heaps, Implementing a Heap, Using a Heap
R
to Implement Heapsort
T

Overview
H

This unit begins by discussing the concept of heaps. Next, the unit describes the application of heap
and definitions of max-heaps and min-heaps. Further, the unit explains the implemention a heap.
IG

Towards the end, the unit highlights the process of using a heap to implement heapsort.
R

Learning Objectives
Y

In this unit, you will learn to:


P

a Discuss the concept of heaps


Explain the concept of applications of heap
O

a Describe the definitions of max-heaps and min-heaps


C

a Explain the significance of implementing a heap


a Understanding the using of heap to implement heapsort
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of heaps
a Assess the concept of applications of heap
a Clarify the definitions of max-heaps and min-heaps
a Determine the significance of implementing a heap

D
a Explore the using of heap to implement heapsort

E
Pre-Unit Preparatory Material

V
a [Link]

R
11.1 INTrOdUcTION

E
A data structure heap is a specialised tree that fulfills all the traits: if P is an antecedent of C, then P has

S
a value either larger or equal to in case of Max-Heaps or lower or equal to in case of min-heap the than
the value of C [1]. The topmost node of the heap without antecedents is referred to as the root.
E
The heap is an effective contrivance of an abstract data type known as priority queue which is usually
R
known as “heaps”, irrespective of the background process of their implementation. Heap is generally
implemented as a binary heap which has the binary tree. A heap is an unorganised structure and can be
thought of as incompletely arranged. Heaps lack the presence of a specific correlation between nodes at
T

any level, even siblings exist without any association. If the heap is a complete binary tree, it possessess
a minimal height—a heap having N nodes with node-wise branches has an invariable height of log
H

N. A heap proves to be an efficient data structure during cases involving element deletion with the
Maximum (or Minimum) preferences or priority.
IG

11.1.1 Operations on Heap


R

The following are the general operations on the heap:


zz Find-max (or find-min): Searches the greatest element in a max-heap or the smallest element in a
Y

min-heap
P

zz Insert: Pushes a new element into the heap


Extract-max (or extract-min): retains the node with the greatest value in a max-heap [or smallest
O

zz
element in a min-heap] post deleting it from the heap
delete-max (or delete-min): deletes the root node of a max-heap (or min-heap)
C

zz

zz replace: Removes existing root value push a new element


zz create-heap: Builds a vacant heap
zz Heapify: Builds a heap from provided elements
zz Merge (union): Attaches two heaps to create a viable new heap having entire elements, conserving
the actual heaps

2
UNIT 11: Heaps JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Meld: Attaches two heaps to create a viable new heap consisting of entire elements of both,
demolishing the actual heaps
zz Inspection: Examines the elements of the heaps
zz Size: Retains the overall count of elements in the heap
zz Is-empty: Retains true when the heap is vacant, else false is returned
zz Increase-key or decrease-key: Modifies a data item present in a max- or min-heap, respectively.
zz delete: Removes the relevant nodes (followed by relocating the final node to sustain heap)

D
zz Sift-up: Transfers a node to the upper levels of the tree, for a required period, reinstates heap after
data addition. Known as “sift” since node travels up in the tree till it arrives at the accurate level

E
zz Sift-down: Transfers a node at the bottom levels in the tree, analogous to sift-up; reinstates heap
after data removal

V
11.2 APPLIcATIONS OF HEAP

R
We can find the application of heaps in popular algorithms like Dijkstra’s algorithm for searching the

E
minimal path. The heapsort algorithm makes use of priority queues. Heaps finds usage in the situations
where we wish to retrieve the largest or smallest data items faster.

S
Heap Data Structure accompanies Heapsort. Heapsort algorithm is rarely used.
E
The applications below utilise Heapsort is as follows:
R
zz Priority Queues: They are executed through Binary Heaps. It completes the functionalities like
data Addition(), Removal() and Find Greatest(), ReduceKey() in O(logn) time. Binomial Heap and
Fibonacci Heap are variants of Binary Heap. They carry out union in O (logn) time which requires
T

O(n) operations in Binary Heap. The priority queues using heaps are applicable in Graph algorithms
like prim’s Algorithm and Dijkstra’s algorithm.
H

zz Order statistics: The Heaps are used effectively to search the nth lowest (or greatest) data item in
IG

an array.
Heapsort is used to subdue the Worst-Case Complexity of Quick Sort procedure from O (n^2) to O(
nlog(n) ).
R

Security Systems and embedded systems like Linux Kernel utilises Heapsort due to time complexity
of O( nlog(n).
Y

11.3 dEFINITIONS OF MAx-HEAPS ANd MIN-HEAPS


P

A heap is a complete binary tree, which can be either a max-heap or min-heap. The max-heap has the
O

property that the key value of any node must be greater than or equal to the key values of its children.
In min-heap, the key value of any node must be lower than or equal to the values of its children.
C

11.3.1 Min-Heap
In a Min-Heap the data item existing at the root node must be lower than or equal to the data values
existing in the descendants. The identical principle is recursively applicable for entire sub-trees
representing a binary trees. Here the lowest data item exists at the root.

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Figure 1 depicts a binary tree which fulfills the criteria of Min-Heap:

Min-Heap

7 12

10 15 17

D
E
Figure 1: Min-Heap
The following C++ program is used to implement min-heap is as follows:

V
#include <iostream>

R
using namespace std;
void min_heap(int *x, int y, int z){

E
int i, k;
k= x[y];
i = 2 * y;
while (i <= z) { S
E
if (i < z && x[i+1] < x[i])
i = i + 1;
R
if (k < x[i])
break;
else if (k >= x[i]) {
T

x[i/2] = x[i];
H

i = 2 * i;
}
IG

}
x[i/2] = k;
return;
}
R

void build_minheap(int *x, int z) {


int k;
Y

for(k = z/2; k >= 1; k--) {


min_heap(x,k,z);
P

}
O

}
int main() {
int z, i;
C

cout<<”Enter no of Elements of Array\n”;


cin>>z;
int x[30];
for (i = 1; i <= z; i++) {
cout<<”Enter element”<<” “<<(i)<<endl;
cin>>x[i];
}
build_minheap(x, z);
cout<<”Min Heap is\n”;
4
UNIT 11: Heaps JGI JAIN
DEEMED-TO-BE UNIVERSITY

for (i = 1; i <= z; i++) {


cout<<x[i]<<endl;
}
}
The output of given C++ code is as follows:
/tmp/GiYHVftMnK.o
Enter no of Elements of Array
7
Enter element 1

D
1
Enter element 2

E
2
Enter element 3

V
3
Enter element 4

R
4
Enter element 5

E
5
Enter element 6
6
Enter element 7 S
E
7
Min Heap is
R
1
2
T

3
4
H

5
6
IG

11.3.2 Max-Heap
R

In a Max-Heap the data items existing at the root node must be larger than or equal to the data items
existing in the descendants. This identical principle holds recursively accurate for entire sub-trees in
Y

respective Binary Tree. Here the largest data item exists at the root. Figure 2 depicts a binary tree that
fulfills the relevant criteria’s for Max-heap:
P
O

Max-Heap
C

17

15 10

6 10 7

Figure 2: Max-Heap

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The following C++ program is used to implement max-heap is as follows:


#include <iostream>
using namespace std;
void max_heap(int *b, int c, int d) {
int x, y;
y = b[c];
x = 2 * c;
while (x <= d) {
if (x < d && b[x+1] > b[x])

D
x = x + 1;
if (y > b[x])
break;

E
else if (y <= b[x]) {

V
b[x / 2] = b[x];
x = 2 * x;

R
}
}

E
b[x/2] = y;
return;
}
void build_maxheap(int *b,int d) {
S
E
int k;
for(k = d/2; k >= 1; k--) {
R
max_heap(b,k,d);
}
}
T

int main() {
H

int n, i;
cout<<”Enter no of Elements of Array:\n”;
cin>>n;
IG

int a[30];
for (i = 1; i <= n; i++) {
cout<<”Enter Elements”<<” “<<(i)<<endl;
R

cin>>a[i];
}
Y

build_maxheap(a,n);
cout<<”Max Heap is:\n”;
P

for (i = 1; i <= n; i++) {


cout<<a[i]<<endl;
O

}
}
C

The output of given C++ code is as follows:


/tmp/GiYHVftMnK.o
Enter no of Elements of Array:
4
Enter Elements 1
11

6
UNIT 11: Heaps JGI JAIN
DEEMED-TO-BE UNIVERSITY

Enter Elements 2
12
Enter Elements 3
13
Enter Elements 4
14
Max Heap is:
14
12
13

D
11

E
11.3.3 Min-Heap vs Max-heap

V
Min-Heap Max-Heap
The data value of min-heap at the root node must be The data item in max-heap existing at the root must be

R
lower than or equal to values of its descendants. larger than or equal to the data items existing in entire
child nodes.

E
Here the least data value exists at the root. Here the largest data item exists at the root.
It works on the increasing priority or preference.
S
It works on decreasing priority or preference.
During its construction, the lowest data item is given During its, construction the largest data item has
E
higher preference. highest preference.
R
Here, the lowest data item is initially removed from the Here, the greatest data item is initially removed from
heap. the heap.
T

11.4 IMPLEMENTINg A HEAP


H

We contrive the Heaps through Arrays. We can reserve a binary tree in an Array. Since a binary heap
is inevitably a complete binary tree, occupies minimal memory space. Additional space is not needed
IG

for pointers; rather, the antecedent and descendant of each node are computed by performing an
arithmetic operation on array indices. These traits present the heap implementation as an illustration
of an implicit data structure or Ahnentafel list. The features rely upon the location of the root, which is
R

dependent on the limitations of the underlying programming language. Occasionally, the root is set at
index 1, to untangle arithmetic calculations.
Y

Assume n as the overall data items in the heap and i as a random logical index of an array holding the
heap. When the root is present at index 0, having indices 0 to n − 1, then every data item a at index i
P

possess the following points:


O

zz Descendants at indices 2i + 1 and 2i + 2


zz Antecedents at index floor((i − 1) ∕ 2).
C

Conversely, when the root is at index 1, having indices 1 to n, then every data item a at index i possess
the following points:
zz Successors at indices 2i and 2i +1
zz Antecedents at index floor(i ∕ 2).

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

This contrivance is utilised in the process of heapsort, where it permits the reutilisation of space in the
input array to hold the heap. The utilise heaps to implement a Priority queue which uses dynamic array
permitting data addition without restrictions, as shown in Figure 3:

0 1 2 3 4 5 6

D
Figure 3: Implementation of Heap through Array

E
Furthermore, we can implement a binary heap with a classic binary tree data structure, but it is
troublesome to search the adjoining data item at the final level of the binary heap during insertion. This

V
data item is evaluated algorithmically or by inserting additional data to the nodes, known as “threading”
the tree—rather than reserving references to the child nodes, we reserve the in order descendant of the

R
node.

E
11.5 USINg A HEAP TO IMPLEMENTINg HEAPSOrT

S
Heapsort is a contrast-dependent data arrangement mechanism using Binary Heap data structure. It
resembles selection sort in which we initially search the low valued element and place it at the position.
E
We iterate the technique again for the leftover data items.
R

11.5.1 Understanding Binary Heap


A binary heap is a complete binary tree. All layers until the last are filled in a complete binary tree. The
T

keys are as far to the left as possible in the final level which satisfied the heap property. Depending on
H

the heap property it satisfies, the binary heap can be either max or min-heap.
A Binary Heap refers to the binary tree having the charareristics are as follows:
IG

zz It refers to a complete tree (where all levels are fully occupied excluding the final level which has
entire keys inclined to the left). This trait of Binary Heap suits it to be reserved in an array.
R

zz A Binary Heap could be classified into Min-Heap or Max-Heap. In a Min Binary Heap, the element
value at the root must be lowest amidst of entire elements existing in the Binary Heap. The identical
principle holds recursively true for entire nodes in Binary Tree. Max Binary Heap resembles Min-
Y

Heap.
P

To comprehend the Binary heaps, one must have an in-depth understanding of a Complete Binary tree.
O

A complete binary tree refers to the binary tree where all the levels, excluding the final level, are fully
occupied and entire nodes are inclined to the left. A Binary Heap refers to a Complete Binary Tree in
which data is held in a specific manner, such that the element in a parent node is larger for Max-heap
C

(or lowest for Min-Heap) as compared to the values of the child nodes. The heap can be denoted using a
binary tree or array.

11.5.2 Array representation of Binary Heap


A Binary Heap can be smoothly denoted through an array and such representation is space-efficient.
If we reserve the parent node at index I, its left child is computed as 2 * I + 1 and right child as 2 * I + 2
(Supposing the index begins at 0).

8
UNIT 11: Heaps JGI JAIN
DEEMED-TO-BE UNIVERSITY

A Binary Heap refers to a Complete Binary Tree. We make use of arrays to represent Binary Heap.
The data item of Root is placed at Arr[0].
The following points displays the indexes of different nodes,Arr[I] indicates i th node.
zz Arr[(i-1)/2]: denotes the parent node
zz Arr[(2*i)+1]: denotes the left child node
zz Arr[(2*i)+2]: denotes the right child node

Figure 4 depicts array representation of binary heap:

D
The traversal technique to attain

E
0
1

V
1
3 6 2

R
3 4
5 9 8 5

E
0
1
1
3
2
6 5
3
S 9
4
8
5
E
Figure 4: Array representation of Binary Heap
R
Array representation is Level Order.
An algorithm of Heapsort in ascending order is as follows:
T

zz Create a max-heap from the scanned data.


H

zz Initially the greatest data value is held at the root. Reinstate it with the final data value of the heap
and decrease the heap size by 1. Ultimately, heapify the root node.
IG

zz Iterate step 2 as long as the heap size is larger than 1.

11.5.2 construction of Heap


R

The technique Heapify applies to a node only if its child nodes are heapified. Hence heapification must
Y

be carried out following a bottom-up approach.


P

Consider the following example is as follows:


Scanned values: 4, 10, 3, 5, 1
O

4(0)
C

/ \
10(1) 3(2)
/ \
5(3) 1(4)

9
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The numbers in braces denote the array indices.


Implementing heapify technique at index 1:
4(0)
/ \
10(1) 3(2)
/ \

D
5(3) 1(4)
Implementing heapify technique to index 0:

E
10(0)

V
/ \

R
5(1) 3(2)

E
/ \
4(3) 1(4)

S
The technique heapify calls itself recursively to create heap.
E
R
Conclusion 11.6 cONcLUSION

zz A heap is an unorganised structure and can be thought as incompletely arranged.


T

zz We can find the application of heaps in popular algorithms like Dijkstra’s algorithm for searching
the minimal path.
H

zz In a Min-Heap the data item existing at the root node must be lower than or equal to the data values
IG

existing in the descendants.


zz In a Max-Heap the data items existing at the root node must be larger than or equal to the data
items existing in the descendants.
R

zz A binary heap is a complete binary tree.


zz Heapsort is a contrast dependent data arrangement mechanism using Binary Heap data structure.
Y
P

11.7 gLOSSAry
O

zz Heap: It is a specialised Data Structure belonging to the class of trees where the tree is complete
binary tree.
C

zz Priority queue: it is an abstract data type resembling the queue data structure where the individual
elements possesses a “Priority” or preference.
zz Binary heap: it is a class of heap data structure which exists as binary tree.
zz dijkstra’s algorithm: It is an algorithm for searching the minimal pathways amongst the nodes in
a graph.
zz Max-heap: It is a class of heap, where the data value in the interior nodes is larger or equal to the
values of the children of the specified node.

10
UNIT 11: Heaps JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Min-heap: It is the data item existing at the root node must be lower than or equal to the data values
existing in the descendants.
zz Binary heap: It is a complete binary tree.
zz Heapsort: It is a contrast dependent data arrangement mechanism using Binary Heap data
structure.

11.8 SELF-ASSESSMENT QUESTIONS

D
A. Multiple choice Questions

E
1. Which of the following denotes a node of a max-heap having the largest key value?

V
a. Leaf node
b. Initial node of the left sub tree

R
c. Root node

E
d. Initial node of the right sub tree.
2. Choose the time complexity of inserting a data item into the heap?
a. O(log n) S
E
b. O(h)
R
c. O(log n) & O(h)
d. O(n)
T

3. The worst-case complexity of removing any random node from the heap is __________.
H

a. O(logn)
b. O(n)
IG

c. O(nlogn)
d. O(n2)
R

4. Which among the following is an unorganised structure and can be thought of as incompletely
arranged?
Y

a. Heap
P

b. Array
O

c. Binary tree
d. Nodes
C

5. Transfer a node at the bottom levels in the tree, analogous, reinstates heap after data removal is
known as:
a. Sift-up
b. Sift-down
c. Create-heap
d. Inspection

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

6. Choose from the options below the heap where the root node must be largest between the keys
located at entire child node’s position.
a. min-heap
b. max-heap
c. Binary heap
d. Heapsort
7. Which among the following operations retains the overall count of elements in the heap?

D
a. Insert
b. Replace

E
c. Size

V
d. Delete
8. __________ completes the functionalities like data Addition(), Removal() and Find Greatest(),

R
ReduceKey() in O(logn) time.
a. Array

E
b. Priority queues
c. Order statistics
S
E
d. Heap
9. A Binary Heap can be smoothly denoted through an array and such representation is:
R

a. Space-efficient
b. Time-efficient
T

c. Complexity-efficient
H

d. Size-efficient
IG

10. __________ build a heap from provided elements.


a. Delete
b. Merge
R

c. Meld
Y

d. Heapify
P

B. Essay Type Questions


O

1. A data structure heap is a specialised tree which fulfills all the traits. State the concept of Heap.
2. A heap is a complete binary tree, which can be either max-heap or min-heap. Explain the significance
C

of min and max heaps.


3. Describe the concept of binary heap.
4. We contrive the Heaps through Arrays. We can reserve a binary tree in an Array. Clarify how a heap
can be implemented.
5. We can find the application of heaps in popular algorithms like Dijkstra’s algorithm for searching
the minimal path. Describe the applications of heaps.

12
UNIT 11: Heaps JGI JAIN
DEEMED-TO-BE UNIVERSITY

11.9 ANSWErS ANd HINTS FOr SELF-ASSESSMENT QUESTIONS

A. Answers to Multiple choice Questions

Q. No. Answer
1. c. Root node
2. c. O(log n) & O(h)

D
3. a. O(logn)

E
4. a. Heap

V
5. b. Sift-down
6. b. max-heap

R
7. c. Size

E
8. b. Priority queues
9.
10.
a. Space-efficient
d. Heapify S
E
B. Hints for Essay Type Questions
R

1. The heap is an effective contrivance of an abstract data type known as priority queue which are
usually known as “heaps”, irrespective of the background process of their implementation. Refer to
T

Section Introduction
H

2. The max-heap has the property that the key value of any node must be greater than or equal to the
key values of its children. In min-heap, the key value of any node must be lower than or equal to the
IG

values of its children. Refer to Section Definitions of Max-Heaps and Min Heaps
3. A binary heap is a complete binary tree. All layers until the last are completely filled in a complete
binary tree. Refer to Section Using a Heap to Implementing Heapsort
R

4. Assume n as the overall data items in the heap and i as random logical index of an array holding the
heap. When the root is present at index 0, having indices 0 to n − 1, then every data item a at index i
Y

possess:
P

z Descendants at indices 2i + 1 and 2i + 2


O

z Antecedents at index floor((i − 1) ∕ 2).


Refer to Section Implementing a Heap
C

5. The applications below utilise Heapsort is as follows:


z Priority Queues: They are executed through Binary Heaps. It completes the functionalities like
data Addition(), Removal() and Find Greatest(), ReduceKey() in O(logn) time. Binomoial Heap
and Fibonacci Heap are variants of Binary Heap.
Refer to Section Applications of Heap

13
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

@ 11.10 POST-UNIT rEAdINg MATErIAL

zz [Link]
zz [Link]

11.11 TOPIcS FOr dIScUSSION FOrUMS

D
zz Discuss with your friends and classmates about the concept of heaps, implementations of heaps and
its various operations. Also, discuss about the applications of heap with real world examples.

E
V
R
E
S
E
R
T
H
IG
R
Y
P
O
C

14
UNIT

12

D
E
Graphs

V
R
E
Names of Sub-Units
S
E
Graph Terminology, Directed and Undirected Graph, Adjacency List and Adjacency Matrix
R
Representation of Graphs, Elementary Graph Operations, Traversal Methods
T

Overview
H

This unit begins by discussing about the concept of graphs and graph terminologies. Next, the unit
describes the directed and undirected graph. Further, the unit explains the matrix and adjacency list
IG

representation of graphs and elementary graph operations. Towards the end, the unit analyses the
traversal methods.
R

Learning Objectives
Y

In this unit, you will learn to:


P

a Discuss the concept of graphs


O

a Explain the concept of graph terminologies and directed and undirected graph
a Describe the matrix and adjacency list representation of graphs
C

a Outline the significance of elementary graph operations


a Elucidate the importance of traversal methods
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of graphs
a Assess the concept of graph terminologies and directed and undirected graph
a Evaluate the importance of matrix and adjacency list representation of graphs
a Determine the significance of elementary graph operations

D
a Understand the importance of traversal methods

E
Pre-Unit Preparatory Material

V
[Link]

R
a

E
12.1 INTrOdUcTION

S
A graph is a sort of a tree (with or without cycles), in which each node is called a vertex and is connected
with lines, called edges. The set of vertices is represented by V and the set of edges is represented by E.
E
Hence, a graph is designated as: G = (V, E). For example, the graph shown in Figure 1 has a set of vertices:
V={d,a,b,c} and a set of edges: E={(d,a), (a,b),(a,c)}.
R

The degree of a vertex is the number of edges that are joined to that vertex, i.e., the number of neighbors
it has. If the vertex a has three neighbors: b, c, d, then the degree of vertex a is said to be 3, as shown in
T

Figure 1:
H
IG

d a
R

c
Y
P

Figure 1: Graph
O

A graph is said to be a simple graph if:


C

zz It has no cycles. A cycle is an edge of a node that connects to itself)


zz No more than one edge joins any pair of nodes

In the graph shown in Figure 1, the edges do not have any direction, i.e., there is no starting or ending
vertices. The edge (d, a) can also be written as (a, d) which depicts that there is an edge connecting
the vertices, d and a. Since there is no direction in the edges, this graph can also be called “Undirected
Graph”.

2
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

We can assign direction to the edges of this graph, as shown in the Figure 2:

d a

D
c

E
V
Figure 2: A directed Graph has directions to its edges

R
The Graph shown in Figure 2 has directions attached to its edges and is hence called a Directed Graph.
Since the edges connecting the two vertices have a direction, we term one of the edges as a starting

E
vertex and the other as the ending vertex. For example, let’s observe an edge in the preceding graph:
(a,d), it represents that there is an edge from vertex a to vertex d (vertex a can be called as starting
S
vertex and vertex d can be called as ending vertex. The set of edges: E of the graph shown above can be
E
written as {(a,d), (a,b), (a,c)}.
We learn about graphs, their different types and about where they are applied. You also learn about the
R
methods, Adjacency Matrix and Adjacency List, which are used to represent graphs on computer. You
also learn about how to traverse a graph using the Breadth First Traversal and Depth First Traversal
methods.
T
H

12.1.1 Graph data Structure


IG

Statistical graphs could be depicted using the data structure. A graph is represented through an array
holding vertices and a single-dimensional array consisting of edges. Before moving ahead, let’s get
acquainted with certain significant terms are as follows:
R

zz Vertex: Every node in a graph is called a vertex. In the image below, the marked circle denotes vertices.
The circles from, A to G denotes vertices. They are represented through an array as displayed in the
figure 3. A is recognised through index 0. B is recognised through index 1 and the pattern continues.
Y

zz Edge: Edge indicates a way or a line among two vertices. In the figure 3, the lines from A to B, B
P

to C, etc. denotes edges. A two-dimensional array is utilised to depict an array as displayed in the
figure 3. Here AB is denoted as 1 at row 0, column 1, BC as 1 at row 1, column 2, etc., making remaining
O

coalescence as 0.
Adjacency: Dual nodes or vertices become adjacent when they are linked among themselves by an
C

zz
edge. In figure 3, B and A are adjacent nodes, C and B are adjacent nodes, etc.
zz Path: Path denotes a series of edges among the two vertices. In the figure 3, ABCD indicates a path
from A to D.

3
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Figure 3 depicts a graph according to the above points:

0 A

1 B 4 E 5 F

D
E
2 C 6 G

V
R
E
3 D

S
E
Figure 3: A Graph data Structure
The fundamental operations of the graph are as follows:
R
zz Add vertex: Inserting a vertex to the graph.
zz Add edge: Inserting an edge amidst two vertices in a graph.
T

zz display vertex: Showing a vertex of a graph.


H

12.2 GrAPH TErMINOLOGY


IG

The graph data structure has multiple terminologies which are as follows:-
zz Vertex: Individual data element of a graph is called Vertex. It is also known as a node. In the above
example graph, A, B, C, D & E are known as vertices.
R

zz Edge: An edge refers to interconnected linkage among two vertices. Alternatively, an edge is termed
as an Arc. An edge has a (Starting Vertex and an Ending Vertex). For instance, the graph above has
Y

the link among vertices A and B denoted as (A,B). On the whole, 7 edges (i.e., (A, B), (A, C), (A, D), (B,
P

D), (B, E), (C, D) and (D, E) exists. Edges are divided into three classes:
Undirected edge: refers to a bidirectional edge. When an undirected edge exist among vertices
O

z
A and B then edge (A, B) and edge (B, A) are identical.
directed edge: refers to the unidirectional edge. When a directed edge exists among vertices A
C

z
and B then edge (A, B) is unequal to edge (B, A).
z Weighted edge: refers to an edge having assigned value (price) to it.
zz Undirected graph: A graph having undirected edges alone is termed as undirected graph.
zz directed graph: A graph having directed edges alone is called as directed graph.
zz Mixed graph: A graph having the undirected as well as the directed edges is called as mixed graph.

4
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz End vertices or endpoints: The dual vertices connected through an edge are termed as end vertices
(or End points) of the specific edge.
zz Origin: In a directed edge, the initial terminating point is called as its origin.
zz destination: In a directed edge, its initial terminating point is called its origin and another
terminating point is called as the destination of the specific edge.
zz Adjacent: If an edge exists amidst of vertices A and B then they are termed as adjacent.
zz Incident: An Edge is an incident on a vertex when the vertex becomes one of the terminating points
of the specific edge.

D
zz Outgoing edge: A directed edge is called as the outgoing edge of the source vertex.

E
zz Incoming edge: A directed edge is called as the incoming edge on the target vertex.
zz degree: Overall count of edges linked to a vertex is termed as the degree of the vertex.

V
zz Indegree: Overall count of incoming edges linked to a vertex is termed as indegree of the vertex.

R
zz Outdegree: Overall count of outgoing edges linked to a vertex is termed as outdegree of the vertex.
Parallel edges or multiple edges: When two directionless edges have common terminating vertices

E
zz
and two directed edges having common source and destination, exists, we term such edges as
parallel edges or multiple edges.
zz S
Self-loop: Edge (undirected or directed) becomes self-loop when its two terminating points concur.
E
zz Simple graph: A graph is called simple when no parallel and auto-loop edges exist.
R
zz Path: A path refers to a series of intermittent vertices and edges which initiates at one vertex and
terminates at another vertex where each edge connects the antecedent and descendant vertices.
T

12.3 dIrEcTEd ANd UNdIrEcTEd GrAPHS


H

A collection or a set of vertices of directed edges that links with an individual ordered pair of vertices is
known as a directed graph or it is also termed as a digraph.
IG

It possesses directed edges, which denote a one-way relationship, where individual edges could be
traversed in a unidirectional way alone. The image displays a directed graph having three nodes and
two edges. The accurate location, size or alignment of the edges in a graph depiction is meaningless
R

as a graph can be interpreted in various forms by reshuffling the nodes and/or deforming the edges,
provided the primary structure stays unchanged. Figure 4 depicts a directed graph:
Y
P
O
C

Figure 4: directed Graph

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

12.3.1 General Application for directed Graphs


Directed graphs are essential for the designing of specific classes of concrete structures. A general
directed graph is a genealogical or phylogenetic tree that plots the relationship among successors and
their antecedents.

12.3.2 Undirected Graphs


It is a set of nodes and of links among the nodes are known as an undirected graph. An individual node
is termed as vertex and an individual link is termed as edge, which connects two vertices. An undirected

D
graph contains a fixed set of vertices and a fixed set of edges together.
It possesses directionless edges. The edges denote a two-way correspondence, in which every edge could

E
be travelled in both directions. Figure 5 displays an undirected graph:

V
R
E
S
E
R
T

Figure 5: Undirected Graph


H

12.3.3 General Applications of Undirected Graphs


IG

One of the famous undirected graphs in the world of computers is the topology of links with respect to
a computer network. The graph is undirected to manifest the interconnection persisting among nodes.
Other recognised instances of undirected graphs are the topology of social networking platforms.
R

12.4 AdjAcENcY LIST ANd AdjAcENcY MATrIx rEPrESENTATION OF GrAPHS


Y

Diagrammatically, it is easy to represent graphs by making vertices and lines connecting them in the
form of edges. However, representing them in the form of a computer program is a bit critical. Therefore,
P

we need to develop some notations to represent vertices and edges. There are mainly two methods of
O

representing graphs:
zz Adjacency matrix
C

zz Adjacency list

12.4.1 Adjacency Matrix


Adjacency Matrix is a method by which we represent a graph in the form of a matrix. The first row and
first column of a matrix represent the vertices and the rest of the elements represent the edges. The
elements are represented as m and jij, where i is the row number and j is the column number, and it

6
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

represents the edge from vertex i to vertex j. The value of the element mij is set to 1 if there is an edge
from vertex i to vertex j; otherwise, its value is set to 0. Consider the graph shown in Figure 6:

1 2

4 5

D
E
Figure 6: A Graph
Now, its adjacency matrix representation is:

V
5, 5 1 2 3 4 5

R
101000

E
201101
300001
S
E
410101
500000
R

The first row and first column represent the vertices. If there is an edge between the vertices, i and j,
then it will be the one at the intersection of the ith row and jth columns. However, the absence of an
T

edge between i and j will be represented by 0. The number of non-zero elements of an adjacency matrix
H

indicates the number of edges in a directed graph.


Following are the advantages of representing an adjacency matrix:
IG

zz The degree of any vertex “i” of an undirected graph can be easily computed from the adjacency
matrix of that graph, just by counting the number of 1s in the i-th row. In the case of a directed
graph, the in-degree (the number of edges having the direction towards the vertex) of a vertex ’’i”
R

is the number of 1s in the i-th column and the out-degree (the number of edges with direction away
from the vertex) of “i” is the number of 1s in the ith row of the adjacency matrix.
Y

zz An adjacency matrix is also suitable to represent a weighted graph. Instead of assigning “1” to the
element mij (when there is an edge from vertex i to vertex j), the weight of the edge is assigned to the
P

element. This means that if the weight of the edge from vertex I to vertex j is 5, then the value of the
O

element mij is set to 5. If there is no edge in between the vertices i and j, then infinity is assigned to
the element mij.
C

Following are the drawbacks of representing an adjacency matrix:


zz This representation requires n2 elements to represent a graph having ’n’ vertices (as the first row
and first column of the matrix represent the vertices). If a directed graph has “e” edges, then the
number of elements in the matrix having the 0 value is n2-e. So, there is a lot of memory wastage if
the number of edges is less in a graph.
zz Parallel edges cannot be represented by an adjacency matrix.

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The following C++ program is used to implement adjacency matrix are as follows:
#include<iostream>
using namespace std;
int vertArr[10][10]; //the adjacency matrix initially 0
int count = 0;
void DisplayMatrix(int V) {
int i, j;
for(i = 0; i < V; i++) {
for(j = 0; j < V; j++) {

D
cout << vertArr[i][j] << " ";
}
cout << endl;

E
}

V
}
void add_edge(int U, int V) {

R
vertArr[U][V] = 1;
vertArr[V][U] = 1;

E
}
main(int argc, char* argv[]) {
int V = 6;
add_edge(0, 4);
//six vertices in graph
S
E
add_edge(0, 3);
add_edge(1, 3);
R
add_edge(2, 4);
add_edge(1, 4);
add_edge(3, 2);
T

add_edge(5, 4);
H

add_edge(5, 2);
add_edge(3, 4);
DisplayMatrix(V);
IG

}
The output of given C++ code is as follows:
R

/tmp/06m2U4mQ5U.o
0 0 0 1 1 0
Y

0 0 0 1 1 0
0 0 0 1 1 1
P

1 1 1 0 1 0
1 1 1 1 0 1
O

0 0 1 0 1 0
C

12.4.2 Adjacency List


Adjacency list is an efficient means of representing a graph G= (V, E) where V is a set of all the vertices
and E is a set of all the edges in the graph G. It uses linked lists of adjacent vertices for all the vertices in
’V’. This approach creates separate linked lists for each vertex in ’V’.

8
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

Let us consider the graph shown in Figure 7:

a b

e d

Figure 7: A Graph

D
Now, to view its Adjacency List representation, you can have a look at Figure 8:

E
1st
v e v e v e

V
a b d NULL

b d NULL

R
c b d NULL

E
d d e NULL

e a c
S NULL
E
Figure 8: Adjacency List representation
R
It generally uses less memory when a large number of vertices and a small number of edges are
contained in a graph. The total number of nodes in an adjacency list for an undirected graph with “n”
vertices and “e” edges are (n+2e); and the same for a directed graph is (n+ e).
T

If “e” is very large, then due to the overhead of maintaining pointers, the adjacency list representation
H

may become more wasteful as compared to the adjacency matrix representation.


The degree of a vertex in an undirected graph is the length of the list pointed to by that vertex, but the
IG

computation of in-degree of a vertex in a directed graph may require O(e): number of comparisons, as
all the lists pointed to by all the vertices may have to be examined.
R

In ’C++’ language, the adjacency list of a graph may be represented by an array of pointers. Each pointer
points to a linked list of the vertices adjacent to a particular vertex. The number of elements of the array
Y

would be equal to the number of vertices present in the graph.


P

The following C++ program is used to implement adjacency list are as follows:
#include<iostream>
O

#include<list>
#include<iterator>
C

using namespace std;


void DisplayAdjList(list<int> Adj_List[], int V) {
for(int i = 0; i<V; i++) {
cout << i << "--->";
list<int> :: iterator it;
for(it = Adj_List[i].begin(); it != Adj_List[i].end(); ++it) {
cout << *it << " ";
}

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

cout << endl;


}
}
void add_edge(list<int> adj_list[], int x, int y) {
adj_list[x].push_back(y);
adj_list[y].push_back(x);
}
main(int argc, char* argv[]) {
int v = 6; // total six vertices are there in the graph
list<int> adj_list[v];

D
add_edge(adj_list, 0, 2);
add_edge(adj_list, 0, 4);

E
add_edge(adj_list, 0, 5);
add_edge(adj_list, 1, 5);

V
add_edge(adj_list, 1, 4);
add_edge(adj_list, 2, 3);

R
add_edge(adj_list, 2, 2);
add_edge(adj_list, 5, 3);

E
add_edge(adj_list, 5, 4);
DisplayAdjList(adj_list, v);
}
S
E
The output of given C++ code is as follows:
/tmp/06m2U4mQ5U.o
R
0--->2 4 5
1--->5 4
T

2--->0 3 2 2
3--->2 5
H

4--->0 1 5
5--->0 1 3 4
IG

12.5 ELEMENTArY GrAPH OPErATIONS


Provided a graph G = (V E) and a vertex v in V (G). To view entire vertices in G which are traceable from v
R

(i.e., complete vertices which are linked to v). We have two methods of achieving this: depth-first search
and breadth-first search. They function on the directed as well as on undirected graphs. The upcoming
Y

discourse considers directionless graphs.


P

12.6 TrAVErSAL
O

Traversal of a graph means visiting the vertices of the graph and displaying them on the screen.
However, the approach that is used in deciding which adjacent vertex has to be visited next (from the
current vertex) decides the type of traversal. There are two types of traversals for a graph:
C

zz Depth first traversal


zz Breadth first traversal

12.6.1 depth First Traversal


Depth First Traversal tends to create very long and narrow trees. In this traversal, we start at some
vertex v, process it (display it) and then recursively traverse all the adjacent vertices.

10
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

This traversal creates a spanning forest that can be used to determine if an undirected graph is
connected and then to identify the connected components of that undirected graph. We take the help of
a stack structure for Breadth First Traversal of a graph. Now, let us consider the graph whose depth first
traversal is required, as shown in Figure 9:

a b

e d

D
The Adjacency List representation of this graph is shown in Figure 9:

E
1st

V
v e v e v e
a b d NULL

R
b d NULL

E
c b d NULL

d d e NULL

e a c S NULL
E
We begin the traversal from vertex a. We first store vertex a into a stack, as shown in Figure 10:
R
T
H

a top
IG

Figure 10: Vertex a Stored into a Stack


Then, we pop it out from the stack and check whether it is marked Y or N. If it is marked N, it means that
R

it is not yet visited; so we visit it, i.e., we display the vertex on the screen and set its marked attribute m
to Y (so that is should not be visited again in future). Then, all the nodes connected to the adjacency list
Y

of vertex a, i.e., node b and node d are pushed into the stack, as shown in Figure 11:
P

STACK
O

a
d top
C

visited
b

Figure 11: Node b and d are Pushed into the Stack


Now, node d is popped out from the stack and again its marked field, m is checked. If it is N, it is visited,
i.e., printed or displayed. After that, its marked field m is set to Y and its adjacency list nodes, i.e., d and
e are checked for their m field. If any of them is N, it is pushed into the stack.

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Now, since d is already Y, it is not pushed into the stack but node e is pushed into the stack, as shown in
Figure 12:

STACK

a, d
e top
visited
b

Figure 12: Node e is Pushed into the Stack

D
Now, e is popped out from the stack, since its field m is marked N, i.e., it is visited. After visiting node I,
its m field is set to “Y” and its adjacency list nodes, i.e., a and c are checked, and the nodes having m field

E
equal to N are pushed into the stack. Now, since a is marked Y, we do not enter it into the stack again, but
node c is pushed into the stack, as shown in Figure 13:

V
R
STACK

E
a, d, e
c top
visited
b

S
E
Figure 13: Node c is Pushed In
Now, node c is popped out from the stack, and its marked field m is checked. Since it is N, it is visited and
R
its marked field is set to Y and then its adjacency list nodes, b and d are checked. If any of these nodes
have their m field set to N, they are pushed into the stack.
T

Now since d is marked Y, it is not pushed into the stack, but b is pushed, as shown in Figure 14:
H

STACK
IG

a, d, e, c
b top
visited
b
R

Figure 14: Node b is Pushed into the Stack


Y

Now, the next element b is popped out from the stack. Its marked field m is checked and since it’s set to
N, it is visited. After that, its m field is set to Y and its adjacency list node d is checked. However, since its
P

m field is set to N, it is not pushed in. Then, the last node b in the stack is popped out, and since its m field
O

is already set to Y, it is not visited. Hence, the depth first traversal of the graph can be shown as: a,d,e,c,b
The following C++ program is used to implement Depth first search are as follows:
C

#include <iostream>
#include <list>
using namespace std;
class DFSGraph
{
int v; // No. of vertices
list<int> *adjList;
void DFS_util(int v, bool visited[]);

12
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

public:
// Constructor of a class
DFSGraph(int V)
{
this->v = V;
adjList = new list<int>[V];
}
void addEdge(int x, int y){
adjList[x].push_back(y);
}

D
void DFS();

E
};
void DFSGraph::DFS_util(int v, bool visited[])

V
{
visited[v] = true;

R
cout << v << " ";

E
//Process all the adjacent vertices of node recursively
list<int>::iterator i;

S
for(i = adjList[v].begin(); i != adjList[v].end(); ++i)
if(!visited[*i])
E
DFS_util(*i, visited);
}
R
void DFSGraph::DFS()
{
bool *visited = new bool[v];
T

for (int i = 0; i < v; i++)


visited[i] = false;
H

// Analyse the vertices one by one by recursively


IG

for (int i = 0; i < v; i++)


if (visited[i] == false)
DFS_util(i, visited);
R

int main()
Y

{
P

// Create a graph
DFSGraph gdfs(5);
O

[Link](0, 2);
[Link](0, 3);
[Link](0, 4);
C

[Link](1,3);
[Link](2, 1);
[Link](3, 3);
[Link](3, 4);
cout << "Depth-First Traversal for the Given Graph is:"<<endl;
[Link]();
return 0;
}

13
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The output of given C++ code is as follows:


/tmp/O6tCuX54rt.o
Depth-First Traversal for the Given Graph is:
0 2 1 3 4

12.6.2 Breadth First Traversal


Traversal means visiting each of the vertices of a graph, exactly once. Breadth First Traversal is the
traversal that tends to create very wide short trees. It operates by vertices in layers, i.e., the vertices
closest to the start are evaluated first and the most distant vertices are evaluated last. Hence, we can

D
say that Breadth First Traversal is the level-by-level traversal of a tree.

E
Breadth First Traversal is used to determine whether a graph is cyclic or not. For a directed graph, this is
detected when a back edge is found. For an undirected graph, it is detected when a cross edge within the

V
same tree is found. This traversal can also be used to find the shortest path from one node to another.
We take the help of a Queue structure for the Breadth First Traversal of a Graph.

R
In the preceding code, we are considering a graph whose Breadth First Traversal is required. You can
find such a graph in Figure 15:

E
a

S b
E
c
R
e d
T

Figure 15: A Graph


The Adjacency List representation of this graph is shown in Figure 16:
H

1st
IG

v e v e v e
a b d NULL

b d NULL
R

c b d NULL
Y

d d e NULL
P

e a c NULL
O

Figure 16: Adjacency List representation


C

In this List representation, we begin our traversal from vertex a. We first store vertex into a queue, as
shown in Figure 17:

f r

Figure 17: Vertex a

14
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

Then, we remove it from the queue and check whether it is marked Y or N. If it is marked N, it means that
it is not yet visited; so we visit it, i.e., we display the vertex on the screen and set its marked attribute m
to Y (so that is should not be visited again in future). Then, all the nodes connected to the adjacency list
of vertex a, i.e., node b and node d, are stored in the queue, as shown in Figure 18:

b d
a
f r visited

Figure 18: Node b and d are Stored in the Queue

D
Now, when we remove node b from the queue, we again check its marked field m. If the marked field is
N, the node is visited, i.e., printed. After this, its marked attribute m is set to Y and its adjacency list node,

E
i.e., d is inserted into the queue, as shown in Figure 19:

V
b is removed from queue and is visited
a, b

R
d
visited
f r

E
Figure 19: Node d is Inserted into the Queue

S
Now, d is removed from the queue, since its field m is marked N, i.e., it is visited. Then, its m field is set to
E
Y and its adjacency list nodes, i.e., d and e are checked, and the nodes which have m field equal to N are
inserted into the queue. Since d is marked Y, it is not entered into the queue again, but node e is added to
R
the queue, as shown in Figure 20:

d is removed and visited


T

d e a, b, d
H

visited
f r it is added into queue
IG

e a, b, d
visited
f r
R

Figure 20: Node e is Added to the Queue


Y

Now, the next element e is removed from the queue. Its marked field m is checked and since it is set to N,
P

node e is visited. Then, its m field is set to Y and its adjacency list nodes, a and c are checked, and if any
of the nodes have their m field set to N, they are added to the queue.
O

Now, since node a is marked Y, it is not added to the queue, but node c is added to the queue, as shown
in Figure 21:
C

e is removed and visited


d a, b, d, e
visited
f r
it is added

Figure 21: Node c is Added to the Queue

15
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Now, node c is removed from the queue and since its marked field m is N, it is visited and is set to Y and
its adjacency elements, b and d are checked. If any of their marked fields represented by m are N, they
are added to the queue. However, since both the nodes have been visited earlier, none is added to the
queue. So, the Breadth First Traversal of the graph can be presented in this order: a,b,d,e,c.
The following C++ program is used to implement breadth first search are as follows:
#include<iostream>
#include <list>
using namespace std;
class Graph

D
{
int v;

E
list<int> *adj;
public:

V
Graph(int v); // Constructor
void addEdge(int a, int b);

R
// Display BFS traversal from a given source S
void BFS(int S);

E
};
Graph::Graph(int v)
{
this->v = v; S
E
adj = new list<int>[v];
}
R
void Graph::addEdge(int a, int b)
{
adj[a].push_back(b);
T

}
void Graph::BFS(int S)
H

{
bool *visited = new bool[v];
IG

for(int i = 0; i < v; i++)


visited[i] = false;
// Create a queue for Breadth First Search
R

list<int> Queue;
// Mark the existing node
visited[S] = true;
Y

Queue.push_back(S);
P

list<int>::iterator i;
while(![Link]())
O

{
S = [Link]();
cout << S << " ";
C

Queue.pop_front();
for (i = adj[S].begin(); i != adj[S].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
Queue.push_back(*i);
}

16
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

}
}
}
// Test the methods of graph class
int main()
{
// Generating a graph
Graph g(4);
[Link](0, 1);
[Link](0, 2);

D
[Link](1, 2);
[Link](2, 3);

E
[Link](2, 0);
[Link](3, 1);

V
cout << " Breadth First Traversal "
<< "(starting from vertex 2) is: \n";

R
[Link](2);
return 0;

E
}
The output of given C++ code is as follows:
/tmp/06m2U4mQ5U.o
S
E
Breadth First Traversal (starting from vertex 2) is:
2 3 0 1
R

12.7 LAB ExErcISE


T

12(a): Write a Program in C++ to implement Graph (G) using nodes and vertices.
H

The following C++ program is used to implement a graph using nodes and vertices are as follows:
// A simple representation of graph using STL
IG

#include <bits/stdc++.h>
using namespace std;
// undirected graph.
R

void addEdge(vector<int> adj[], int a, int b)


{
Y

adj[a].push_back(b);
adj[b].push_back(a);
P

}
void printGraph(vector<int> adj[], int V)
O

{
for (int v = 0; v < V; ++v) {
C

cout << "\n Adjacency list of vertex " << v


<< "\n head ";
for (auto x : adj[v])
cout << "-> " << x;
printf("\n");
}
}
int main()

17
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

{
int V = 5;
vector<int> adj[V];
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 1, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 2, 1);
addEdge(adj, 3, 4);

D
printGraph(adj, V);
return 0;

E
}

V
The output of given C++ code is as follows:
/tmp/U0yXDoXAIp.o

R
Adjacency list of vertex 0
head -> 1-> 4

E
Adjacency list of vertex 1
head -> 0-> 4-> 2-> 3-> 2
Adjacency list of vertex 2
head -> 1-> 1 S
E
Adjacency list of vertex 3
head -> 1-> 4
R
Adjacency list of vertex 4
head -> 0-> 1-> 3
T

12(b): Write a Program in C++ to check whether a given graph is connected or not.
H

The following C++ program is used to check a given graph is connected or not are as follows:
#include<iostream>
IG

#define node 5
using namespace std;
int graph[node][node] = {{0, 1, 0, 0, 0},
R

{0, 0, 1, 0, 0},
{0, 0, 0, 1, 1},
{1, 0, 0, 0, 0},
Y

{0, 1, 0, 0, 0}
P

};
void Traverse(int U, bool visited[]){
O

visited[U] = true;
for(int v = 0; v<node; v++){
C

if(graph[U][v]){
if(!visited[v])
Traverse(v, visited);
}
}
}
bool isConnected(){
bool *vis = new bool[node];

18
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

for(int U; U < node; U++){


for(int i = 0; i<node; i++)
vis[i] = false; //initialize as no node is visited
Traverse(U, vis);
for(int i = 0; i<node; i++){
if(!vis[i]) //Graph is not connected if node is not visited to
the traversal
return false;
}
}

D
return true;
}

E
int main(){
if(isConnected())

V
cout << "The Graph is connected.";
else

R
cout << "The Graph is not connected.";
}

E
The output of given C++ code is as follows:
/tmp/06m2U4mQ5U.o
The Graph is connected. S
E
R
Conclusion 12.8 cONcLUSION

A graph is a sort of a tree (with or without cycles), in which each node is called a vertex and is
T

zz
connected with lines, called edges.
H

zz A graph is called as simple when no parallel and auto-loop edges exist.


zz A graph having the undirected as well as the directed edges is called as mixed graph.
IG

zz An edge refers to interconnected linkage among two vertices.


zz A collection or a set of vertices of directed edges that links with an individual ordered pair of vertices
is known as directed graph.
R

zz It is a set of nodes and links among the nodes is known as an undirected graph.
Y

zz Adjacency Matrix is a method by which we represent a graph in the form of a matrix.


P

zz Traversal of a graph means visiting the vertices of the graph and displaying them on the screen.
Depth First Traversal tends to create very long and narrow trees.
O

zz

zz Breadth First Traversal is the traversal that tends to create very wide short trees.
C

12.9 GLOSSArY

zz Graph: It is a sort of a tree (with or without cycles), in which each node is called a vertex and is
connected with lines, called edges.
zz Simple graph: It is a graph called as simple when no parallel and auto-loop edges exist.
zz Mixed graph: It is a graph having the undirected as well as the directed edges is called mixed graph.

19
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz Edge: It refers to interconnected linkage among two vertices.


zz directed graph: It is a collection or a set of vertices of directed edges that links with an individual
ordered pair of vertices is known as a directed graph.
zz Undirected graph: It is a set of nodes and links among the nodes is known as an undirected graph.
zz Adjacency matrix: It is a method by which we represent a graph in the form of a matrix.
zz Traversal: It means visiting the vertices of the graph and displaying them on the screen.
zz depth first traversal: It tends to create very long and narrow trees.

D
zz Breadth first traversal: It is the traversal that tends to create very wide short trees.

E
12.10 SELF-ASSESSMENT QUESTIONS

V
A. Multiple choice Questions

R
1. Which among the following is a sort of a tree (with or without cycles), in which each node is called a

E
vertex and is connected with lines, called edges?
a. Graph b. Edge
c. Traversal d. S
Adjacency matrix
E
2. ______________ is a method by which we represent a graph in the form of a matrix.
R
a. Adjacency list b. Adjacency matrix
c. Directed graph d. Undirected graph
T

3. Which of these tends to create very long and narrow trees?


H

a. Breadth first traversal b. Graph


c. Depth first traversal d. Adjacency list
IG

4. The overall count of edges linked to a vertex is termed as __________ of the vertex.
a. Adjacent b. Destination
R

c. Origin d. Degree
5. Which among the following refers to a series of intermittent vertices and edges which initiates at one
Y

vertex and terminates at another vertex where each edge connects the antecedent and descendant
vertices?
P

a. Self-loop b. Path
O

c. simple graph d. Mixed graph


6. Which of these is used for the breadth first traversal of a graph?
C

a. Queue b. Stack
c. Array d. Linked list
7. A graph is said to be a simple graph if:
a. Edges connecting two vertices
b. It has no cycles

20
UNIT 12: Graphs JGI JAIN
DEEMED-TO-BE UNIVERSITY

c. More than one edge joins any pair of nodes


d. There is no direction in the edge
8. It indicates a way or a line among two vertices, it is a:
a. Vertex b. Path
c. Adjacency d. Edge
9. Which of these refers to an edge having assigned value (price) to it?
a. Undirected edge b. Directed edge

D
c. Weighted edge d. Origin
10. The total number of nodes in an adjacency list for an undirected graph with “n” vertices and “e”

E
edges is

V
a. (n+2) b. (n+2e)
c. (n) d. (n+1)

R
B. Essay Type Questions

E
1. Define the term Graph.

S
2. It possesses directed edges, which denote a one-way relationship, where individual edge could be
traversed in a unidirectional way alone. Outline the concept of directed graph.
E
3. The approach that is used in deciding which adjacent vertex has to be visited next (from the current
R
vertex) decides the type of traversal. Explain the term traversal and also, discuss its types.
4. Describe the different graph terminologies.
5. It possesses directionless edges. The edges denote a two-way correspondence, in which every edge
T

could be travelled in both directions. Elucidate the concept of undirected graph.


H

12.11 ANSWErS ANd HINTS FOr SELF-ASSESSMENT QUESTIONS


IG

A. Answers to Multiple choice Questions


R

Q. No. Answer
Y

1. a. Graph
P

2. b. Adjacency matrix
3. c. Depth first traversal
O

4. d. Degree
C

5. b. Path
6. a. Queue
7. b. It has no cycles
8. d. Edge
9. c. Weighted edge
10. b. (n+2e)

21
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

B. Hints for Essay Type Questions


1. A graph is a sort of a tree (with or without cycles), in which each node is called a vertex and is
connected with lines, called edges. Refer to Section Introduction
2. A collection or a set of vertices of directed edges that links with an individual ordered pair of vertices
is known as directed graph or it is also termed as digraph. Refer to Section Directed and Undirected
Graphs
3. Traversal of a graph means visiting the vertices of the graph and displaying them on the screen.
There are two types of traversals for a graph:

D
z Depth first traversal

E
z Breadth first traversal
Refer to Section Traversal

V
4. The graph data structure has multiple terminologies which are as follows:-

R
z Vertex: Individual data element of a graph is called as Vertex. It is also known as node. In above
example graph, A, B, C, D & E are known as vertices.

E
z Edge: An edge refers to interconnected linkage among two vertices. Alternatively an edge is

S
termed as an Arc. An edge has a (Starting Vertex and an Ending Vertex). For instance, graph
above has the link among vertices A and B denotes as (A, B). On the whole, 7 edges (i.e., (A, B), (A,
E
C), (A, D), (B, D), (B, E), (C, D) and (D, E) exists.
Refer to Section Graph Terminology
R
5. It is a set of nodes and of links among the nodes is known as undirected graph. An individual node
is termed as vertex and an individual link is termed as edge, which connects two vertices. Refer to
T

Section Directed and Undirected Graphs


H

@ 12.12 POST-UNIT rEAdING MATErIAL


IG

zz [Link]
bpv=1&dq=importance+of+graphs+in+DSA&pg=PA291&printsec=frontcover
R

zz [Link]
Y

12.13 TOPIcS FOr dIScUSSION FOrUMS


P

zz Discuss with your friends and classmates about the concept of graphs and its terminologies. Also,
O

discuss about the traversal of graphs and its effectiveness.


C

22
UNIT

13

D
E
Sorting and Searching

V
R
E
Names of Sub-Units
S
E
Implementation of Sorting Technique, Insertion Sort, Radix Sort, Address Calculation Sort using
Hashing, Searching Algorithms, Linear Search, Binary Search, Jump Search, Interpolation Search
R

Overview
T

This unit begins by discussing about the concept of sorting and searching. Next, the unit outlines
H

the insertion sort, radix sort and address calculation sort. Further, the unit explains the searching
algorithms, sequential search and binary search. Towards the end, the unit covers the jump search
IG

and interpolation search.


R

Learning Objectives
Y

In this unit, you will learn to:


Discuss the concept of sorting and searching
P

a Explain the concept of insertion sort, radix sort and address calculation sort
O

a Describe the searching algorithms and sequential search


Outline the significance of binary search
C

a Discuss the concept jump search and interpolation search

Learning Outcomes

At the end of this unit, you would:


a Assess the concept of insertion sort, radix sort and address calculation sort
a Evaluate the importance of searching algorithms and sequential search
a Determine the significance of binary search
a Understand the concept jump search and interpolation search
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Pre-Unit Preparatory Material

a [Link]

13.1 INTrOdUcTION
Searching and sorting are the two most important tasks applied to data structures. Searching is the
process by which we try to find whether the required data exists in the given structure or not. On the

D
other hand, sorting is a task in which we arrange the given structure in a particular order, i.e., ascending
order or descending order.

E
Since searching in a sorted structure can be quite faster than searching in a non-sorted structure, the
two tasks of searching and sorting are usually collectively applied and due to this, we refer to the two

V
tasks together. Both sorting and searching processes are done by iterating through the elements of a
structure with the help of loops. So, before using any algorithm for sorting and searching, we need to

R
find out its efficiency, i.e., how much time and memory space it would require for sorting or searching
a structure.

E
13.2 IMPLeMeNTaTION Of SOrTINg TechNIqUe
S
Sorting is the process of putting data in a predetermined order. The sorting algorithm specifies how
E
data should be organised in a particular order. Numerical and lexicographical ordering are the two
most common types of order.
R

Sorting is important because it is thought that if data is organised logically data searching would be
substantially enhanced. Data can also be sorted to make it more readable.
T
H

13.2.1 Insertion Sort


In insertion sort, an element is placed at its correct position by moving all the elements greater than this
IG

element to its right. In every pass, the element p[i], is compared with p[i-1], p[i-2]…elements until either
an element smaller than p[i] is found or the beginning of the array is reached. All the elements greater
than p[i] are moved to their right position.
R

Let’s consider the array shown in Figure 1:


Y

5 2 1 7 9 0 4 3 8 6
P

p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] p[8] p[9]
O

figure 1: an array p
As you can see in this array, there are 10 elements and therefore, there will be 9 iterations. During the
C

first iteration, p[1] is compared with p[0]. If p[1] > p[0], then it is fine; otherwise the interchanging takes
place.
During the second iteration, p[2] is compared with p[1] and p[1] with p[0]. Again, if p[2]>p[1], we consider
it to be fine; otherwise, the interchanging of p[2] and p[1] takes place. Then, p[1] and p[0] are compared.
Now, if p[1] >p[0], nothing changes; otherwise, interchanging takes place. Now, let the elements of our
array are:
5217904386

2
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

Hence, in the space below, we move to the iterations related to this array:
zz Iteration 1: p[1] > p[0] is not true: so interchanging take place : 2 5 1 7 9 0 4 3 8 6
zz Iteration 2: p[2] > p[1] is not true, so interchanging of p[2] and p[1] takes place : 2
157
904386
p[1] > p[0] is not true, so interchanging of p[1] and p[0] takes place : 1 2
57

D
904386
zz Iteration 3: In iteration 3, p[3] is compared with p[2], p[2] is compared with p[1] and

E
p[1] is compared with p[0]

V
p[3] >p[2] is true, so no interchanging takes place : 1 2 5 7 9 0 4 3 8 6
p[2] > p[1] is true and p[1] >p[0] is also true, so no more interchanging takes place

R
zz Iteration 4: During iteration 4, p[4] is compared with p[3]: p[3] is compared with p[2]; p[2] is compared

E
with p[1] and p[1] is compared with p[0].
1 2 5 7 9 0 4 3 8 6 ---- Output of iteration 3

S
p[4] > p[3] is true, so no interchanging takes place Similarly, the conditions p[3] >p[2], p[2]>p[1] and
E
p[1] >p[0] are also true: therefore no interchanging is required.
Iteration 5: During iteration 5, p[5] is compared with p[4], p[4] is compared with p[3], p[3] is compared
R
zz
with p[2], p[2] is compared with p[1] and p[1] is compared with p[0].
p[5]>p[4] is not true, so the interchanging of p[5] and p[4] takes place :
T

12
H

57094386
p[4] >p[3] is not true, so the interchanging of p[4] and p[3] takes place :
IG

12
50794386
R

p[3] >p[2] is not true, so the interchanging of p[3] and p[2] takes place :
12
Y

05794386
P

p[2] >p[1] is not true, so the interchanging of p[2] and p[1] takes place :
O

10
25794386
C

p[1] >p[0] is not true, so the interchanging of p[1] and p[0] takes place :
01
25794386
zz Iteration 6: During this iteration also, p[6] is compared with p[5], p[5] with p[4].... p[1] with p[0]. In
other words, p[ j] is compared with p[ j-1] and if in any p[ j]> p[ j-1], we consider the condition to be
true;

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

and therefore, interchanging takes place, as shown in Figures 2 to 5:

Interchanging

0 1 2 5 7 9 4 3 8 6
p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] p[8] p[9]

figure 2: Interchanging Takes Place

D
Interchanging

0 1 2 5 7 4 9 3 8 6

E
p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] p[8] p[9]

V
figure 3: Interchanging Takes Place

R
Interchanging

E
0 1 2 5 4 7 9 3 8 6
p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] p[8] p[9]

S
E
figure 4: Interchanging Takes Place
R
0 1 2 4 5 7 9 3 8 6
p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] p[8] p[9]
T

figure 5: No Interchanging
H

Now, since p[3]>p[2], p[2]>p[1], p[1]>p[0] conditions are true, no more interchanging is desired.
Similarly after iteration 1, our array is like the one shown in Figure 6:
IG

0 1 2 3 4 5 7 9 8 6
p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] p[8] p[9]
R

figure 6: The array after Iteration 1


Y

After iteration 2, the array becomes like the one shown in Figure 7:
P

0 1 2 3 4 5 7 8 9 6
O

p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] p[8] p[9]
C

figure 7: The array after Iteration 2


After the 3rd iteration, our array is sorted as shown in Figure 8:

0 1 2 3 4 5 6 7 8 9
p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] p[8] p[9]

figure 8: The array after Iteration 3

4
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

If the initial file is sorted, then only one comparison is made on each pass; so the number of comparisons
is O(n). If the file is initially sorted in the reverse order, the number of comparisons is O(n2).
The simple insertion sort is considered better than the bubble sort. The closer the file is to the sorted
order, the more efficient the insertion sort becomes. The average number of comparisons in the insertion
sort is also O(n2) and the space requirements for the sort consist of only one temporary variable.
The mechanism of the Insertion sort algorithm resembles the technique when we arrange playing
cards in our hands. We divide the array implicitly into an ordered and an unordered part. Elements are
collected from the unordered portion and are assigned to a suitable location in the ordered portion.

D
algorithm of Insertion Sort

E
To understand this algorithm, let’s consider a function Insertion Sort (p,n). This function states that p is
the array of n elements. Let’s now come to the algorithm for the insertion sort method:

V
Step 1: Initialise a variable, say i to 1
i=1

R
Step 2: Increment the value of i by 1

E
The value of i is incremented by 1 after every iteration, i.e., i=1, 2, 3....
n-1
Repeat the steps 2 to 5 for n-1 times, while i>=n-1 S
E
Step 3: Initialise a variable j to the value of i
R
j=i
Step 4: If p[ j] <p[ j-1], then interchange their values
T

temp=p[ j]
H

p[ j]=p[ j-1]
p[ j-1]=k
IG

Step 5: Repeat step 4 for j >=0


The value of j is decremented by 1 after every iteration i.e. j=i, i-1, i-2,
R

....0

Step 6: Exit
Y

The following C++ program is used to implement the insertion sort are as follows:
P

#include<iostream>
O

using namespace std;


void dis(int *arr, int size) {
for(int i = 0; i<size; i++)
C

cout << arr[i] << " ";


cout << endl;
}
void insertionSort(int *arr, int size) {
int key, j;
for(int i = 1; i<size; i++) {
key = arr[i];

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

j = i;
while(j > 0 && arr[j-1]>key) {
arr[j] = arr[j-1];
j--;
}
arr[j] = key;
}
}
int main() {
int n;

D
cout << "Enter the number of elements: ";
cin >> n;

E
int arr[n];
cout << "Enter elements:" << endl;

V
for(int i = 0; i<n; i++) {
cin >> arr[i];

R
}
cout << "Array before Sorting: ";

E
dis(arr, n);
insertionSort(arr, n);
cout << "Array after Sorting: ";
S
E
dis(arr, n);
}
R
The output of given C++ code is as follows:
/tmp/1hKnRk2uPM.o
T

Enter the number of elements: 4


Enter elements:
H

33 45 66 56
Array before Sorting: 33 45 66 56
IG

Array after Sorting: 33 45 56 66

13.2.2 radix Sort


R

In Radix sort, the numerical data is sorted in n passes, where n is the maximum number of digits in
the numerical data. For example, if the numerical data being sorted consists of 3 digits, the Radix sort
Y

requires 3 passes to sort them. Sorting begins by arranging the numerical data on the basis of LSD
(Least Significant Digit) and with every pass, we move towards MSD (Most Significant Digit). We begin
P

with the LSD and store the numerical data in a two dimensional array in the ascending order of LSD.
In the second pass, the numerical data (that was sorted on LSD) is again placed in the two dimensional
O

array; but this time in the ascending order of the next significant digit. In this way, with every pass, we
move towards the MSD. The last pass consists of storing the numerical data in ascending order of MSD
C

in the two dimensional array.


For example, let the numerical data to be sorted is:
167, 201, 590, 110, 325, 429, 831, 908, 746, 674
The important thing to note here is that the size of all the elements is same, i.e., all elements are 3 digit
numbers. If any numerical has few digits, it is padded with 0’s. For example, if a numerical is 23, it is

6
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

written as 023 to make it of 3 digits. Now, here, since the data is of 3 digits, there are 3 passes to sort this
data.
In the first pass, we store the data in a two dimensional array on the basis of LSD. This means that all
the numerical with LSD as 0, are placed in the 0’th row and all the numerical with LSD as 1 are placed in
the 1st row and so on, as shown in Figure 9:

0 590 110
1 201 831

D
2

E
3
4 674

V
5 325

R
6 746
7 167

E
8 908
9 429
S
E
figure 9: The numerical placed in a two dimensional array on the basis of LSd
R
The numerical data arranged on the basis of LSD is taken out of the two dimensional array. The sequence
of data is: 590, 110, 201, 831, 674, 325, 746, 167, 908 and 429. This data is again placed in the two dimensional
array on the basis of the middle digit. That is, all the numericals with the middle digit as 0 are placed in
T

the 0’th row and all the numerical with the middle digit as 1 are placed in the 1st row and so on, as shown
H

in Figure 10:
IG

0 201 908
1 110
2 325 429
R

3 831
Y

4 746
P

5
6 167
O

7 674
8
C

9 590

figure 10: The numerical placed in two dimensional array on the basis of middle digit
The numerical data arranged on the basis of the middle digit is taken out of the two dimensional array.
The sequence of data will be: 201, 908, 110, 325, 429, 831, 746, 167, 674 and 590. This data is again placed in
the two dimensional array on the basis of MSD.

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

That is, all the numericals with MSD as 0 are placed in the 0’th row and all the numerical with MSD as 1
are placed in the 1st row and so on, as shown in Figure 11:

0
1 110 167
2 201
3 325
4 429

D
5 590

E
6 674
7 746

V
8 831

R
9 908

E
figure 11: The numerical placed in two dimensional array on the basis of MSd

S
We get the numerical sorted as shown in Figure 11. The sorted sequence is 110, 167, 201, 325, 429, 590, 674,
746, 831, and 908. The following C++ program is used to show radix sort is as follows:
E
#include<iostream>
R
#include<list>
#include<cmath>
using namespace std;
T

void Dis(int *Arr, int size) {


for(int i = 0; i<size; i++)
H

cout << Arr[i] << " ";


cout << endl;
IG

}
void radixSort(int *arr, int n, int max) {
int a,b , c, d = 1, index, temperature, count = 0;
R

list<int> pocket[10];
for(a = 0; a< max; a++) {
c = pow(10, a+1);
Y

d = pow(10, a);
P

for(b = 0; b<n; b++) {


temperature = arr[b]%c;
O

index = temperature/d;
pocket[index].push_back(arr[b]);
C

}
count = 0;
for(b = 0; b<10; b++) {
while(!pocket[b].empty()) {
arr[count] = *(pocket[b].begin());
pocket[b].erase(pocket[b].begin());
count++;
}

8
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

}
}
}
int main() {
int n, max;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the maximum digit of elements: ";
cin >> max;
int arr[n]; //create an array with given number of elements

D
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {

E
cin >> arr[i];
}

V
cout << "Data before Sorting: ";
Dis(arr, n);

R
radixSort(arr, n, max);
cout << "Data after Sorting: ";

E
Dis(arr, n);
}
The output of given C++ code is as follows: S
E
/tmp/bItJRqfPru.o
Enter the number of elements: 6
R
Enter the maximum digit of elements: 4
Enter elements:
66 57 99 78 34 44
T

Data before Sorting: 66 57 99 78 34 44


H

Data after Sorting: 34 44 57 66 78 99


IG

applications of radix Sort


In a classic computer, radix sort is utilised for entering the data with various fields. For instance, we
wish to apply sort on 3 fields, i.e., day, month and year. In such a case, Radix sort is applied initially on
R

the date, followed by month, and lastly on year..


It was applied in card arranging devices that possessed 80 columns, and in every column, the device
Y

punched a hole in 12 different positions. The device then arranged the cards, based upon the position
P

where the card was punched, which was utilised by the operator to pile up the cards for which the initial
row was punched, ensued by the 2nd row, the pattern continues till the end.
O

13.2.3 address calculation Sort using hashing


C

Hashing is a technique used for a quick retrieval of the desired data from a large volume of data. This
scheme is used when a record is stored at a particular address and this address is to be computed by
applying a formula: hash function on the key, the primary key of the record. The hash function ( ) is used
in the following manner:
a=h(k)
In this equation, a is the address computed at the time of the application of the hash function on
the k key of the record. The hash function should be selected in such a way that it results in a unique

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

address, every time it is used. However, it is not practically feasible because there are frequent chances
of “collision” i.e. we may get the address of the record with the k1 key, where already a record with the
k2 key is stored. These collided records are called synonyms and we apply certain collision resolution
techniques to resolve the conflict.
The domain of the hashing function is the interval of the key. If the keys are of 3 digits, we say the
domain of the hash function is (0,999). If the keys are of 5 digits, we say that the domain of the hash
function is (0, 99999).
The range of the hash function is the capacity of the storage, where the records are stored. If the array

D
where the records are stored consists of 1000 addresses, we say that the range of the hash function is
(0,999).

E
The hash function should be chosen so that it distributes the keys uniformly over the range of the
storage. If the total capacity of the storage is n, then the good function should distribute the keys over

V
the range (0, n-1).

R
This algorithm makes use of a Hash Function f with the trait of Order Preserving function. The
algorithm utilises an address table to hold the items which persists as a list (or an array) of Linked

E
lists. The Hash function is computed upon the individual value of the array to evaluate the respective
address in the address table. Following this, the elements are entered at their respective locations in an

S
arranged way by contrasting them with the elements existing priory in that address.
E
Post of entering the elements, the elements at every memory location in the address table are arranged.
Therefore we repeat through each memory location individually and enter the data items at that
R
location in the processed array.

13.3 SearchINg aLgOrIThMS


T

The process of searching for a particular data item in a data structure consists of comparison and
H

advancement operations. On the basis of the technique used for locating the required data in a structure,
the searching process is divided into different types. It basically differs in the number of comparisons
IG

done to get the desired data. All the searching processes have one thing in common, which is a result,
which can be either successful or unsuccessful. When the result of a searching process is successful,
it means that the required data is found in the structure and its location is returned. In case of an
unsuccessful result, usually, a boolean value “false” is returned. Common Search types are:
R

zz Linear search
Y

zz Binary search
P

zz Jump search
Interpolation search
O

zz

13.3.1 Linear Search


C

In Linear Search, each record of a file is searched, one at a time, until the desired data is found. The time
required to execute the algorithm is proportional to the number of comparisons. The desired target can
be found at the first iteration or else all the elements may be traversed. So, the average behaviour of
searching in an element array can be stated as:
(1+2+3.....+n)/n = (n+1)/2=O(n)
Hence, for a linear search, the average number of comparisons for a file with n records is n/2 and
the time taken in both the average and worst cases is O(n). In other words, the time complexity of a

10
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

sequential search of an element in an n element array is O(n). On the same basis, we can say that the
time requirement for computing 1+2+3+....+n without using the summation formula is O(n).
To get the maximum value or minimum value in an n element array, we require n-1 comparisons. Hence,
a function to evaluate both the maximum and minimum elements of an array requires 2 (n-1) numbers
of comparisons in the best, worst and average cases.
Function for Linear Search for an Element in an Array:
int search ( int p[], int n, int x)
{

D
int i;
for(i=0;i<n;i++)

E
{
if(p[i]==x)

V
break;
}

R
if (i==n)
return -1;

E
else
return i;
}
S
In this code, the function returns an integer i, if x is found in array p (i is the index of the array, where
E
x is found); otherwise, it returns -1. The comparison starts from the 0th index value of the array and
R
continues until the value x is found in the array or the array is over. Even in an unsuccessful search, the
number of comparisons required to check whether x exists in the array or not is denoted by n. When the
search is unsuccessful, its time complexity is O(n).
T

If the search is successful, the number of comparisons required is one more than the index of the array,
H

where x is found. Therefore, the number of comparisons can be 1,2,3,….. or ’n’, depending on the location
where x is found in the array.
IG

The average behavior of the algorithm for linear search can be written as:
(1+2+3+……+n)n= (n+1)/2 = O(n).
Hence, both the successful and unsuccessful searches have O(n) complexity in the average case. Even in
R

the worst case, the search has O(n) complexity.


Y

13.3.2 Binary Search


P

Binary Search is a search that uses the divide-and-conquer approach. Here, we compare the data to be
O

searched with the data available in the middle of the file (array): If the data to be searched is smaller
than the middle of the array, it means we have to concentrate on the first half of the array and if the
data to be searched is larger than the middle of the array, it means the data will be found in the second
C

half of the array. Then, we compare the data to be searched with the data in the middle of the selected
half, i.e., we determine which quarter of the list contains data. This process is continued until we get the
desired data.
The major drawback of this algorithm is that it assumes that we can directly access the middle value in
the list. This means that the list must be stored in an array. Moreover, the insertion and deletion in an
array is a typical task and requires lots of shuffling of the elements. The complexity of the binary search
algorithm is given by log2 n.

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The maximum number of comparisons required for a successful search is:


2j >= (n+1), where 'j' is the smallest integer
The maximum number of elements that are left after the first comparison is 2(j-1)-1 and the maximum
number of elements left after ’k’ comparisons are 2(j-k)-1. This means that the desired number of
elements can be found after ’j’ comparisons. Therefore, the maximum number of comparisons for a
successful search is given by j, where ’j’ is the smallest integer satisfying the equation 2j. Alternatively,
we can say that the maximum number of comparisons for a successful search can be written as: log2
(n+1).
The numbers of comparisons for a successful as well as an unsuccessful search are approximately given

D
by O(log2 n).

E
Though the binary search requires fewer comparisons, each comparison involves more computation.
The worst case of time complexity in the binary search algorithm is O(log2 n). We can conclude that the

V
number of comparisons in the best case is 1 and the number of comparisons in the worst case is j where
2j >=n+1. The average number of comparisons is represented by log2n.

R
algorithm of Binary Search

E
To understand the algorithm for binary search, let us consider array p. Its length is n and the value to
search is k. After that we can initialise the two variables: lower and upper, as shown in Figure 12:

P[0] S Lower
E
P[1]
P[2]
R

“ Upper
Army
T

figure 12: array p


H

Lower=0
Upper=n (length of array)
IG

The steps used in the algorithm for the binary search are:
zz Step 1: If upper >=lower, then repeat the steps from 2 to 4; else go to step 5
R

zz Step 2: Calculate the middle location of the array by using the following formula:
Y

mid=(lower+upper)/2
zz Step 3: If the value to be searched is found at the location p[mid], then display “Value found” and exit;
P

else go to the next step:


if p[mid]=k
O

print "Value found" and exit


zz Step 4: If the value to be searched is larger than the middle value of the array, then the search is
C

confined to the lower half of the array. So, the lower limit of the array is set to the middle location
of the array:
if k >p[mid]
lower=mid+1
If the value to be searched is smaller than the middle value of the array, then the search is confined
to the upper half of the array. So, the upper limit of the array is set to the middle location of the
array:

12
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

else
upper=mid-1,
zz Step 5: The control appears at this step if the value is not found. Then, you can display “Value not
found” and exit.

13.3.3 Jump Search


The Jump search approach is a new approach for searching a sorted array for a single element.
The primary premise of this searching technique, when compared to a linear search algorithm, is to

D
search a lower number of elements (which scans every element in the array to check if it matches with
the element being searched or not). This can be performed by skipping a specified number of array

E
elements or leaping forward a fixed number of steps in each iteration.
Consider a sorted array A[] of size n, with indexing ranging from 0 to n-1, and a missing element x within

V
the array A[]. This approach also necessitates the use of an p-sized block, which can be as follows:

R
zz Iteration 1: if (x==A[0]), then success and if (x > A[0]), then jump to the next block.
zz Iteration 2: if (x==A[p]), then success and if (x > A[p]), then jump to the next block.

E
zz Iteration 3: if (x==A[2p]), then success and if (x > A[2p]), then jump to the next block.

S
In time at any point, if (x < A[kp]), then a linear search is executed from index A[(k-1)p] to A[kp].
E
Figure 13 depicts the Jump Search technique:
R
Jump Search
T
H

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
IG
R

Linear Search
Y

figure 13: Jump Search Technique


P

algorithm of Jump Search


The following steps describe the algorithm of jump Search is as follows:
O

Step 1: Fix j=0 and p = √n.


C

Step 2: Relate A[ j] with the item. If A[ j] != item and A[ j] < item, then jump to the next block. Also, follow
the following points:
z Set j = p
z Increase p by √n
Step 3: Replicate the step 2 till p < n-1
Step 4: If A[ j] > item, then move to the starting of the present block and do a linear search. Also, follow
the following points:

13
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

z Set x = j
z Equate A[x] with item. If A[x]== item, then print x as the valid location else set x++
z Replicate Step 4.1 and 4.2 till x < p
Step 5: Exit

The following C++ program is used to implement Jump Search algorithm is as follows:
#include <bits/stdc++.h>
using namespace std;

D
int JumpSearch(int array[], int a, int b)
{

E
int Step = sqrt(b);
int previous = 0;

V
while (array[min(Step, b)-1] < a)
{

R
previous = Step;
Step += sqrt(b);

E
if (previous >= b)
return -1;
}
while (array[previous] < a) S
E
{
previous++;
R
if (previous == min(Step, b))
return -1;
}
T

// If the element is found


H

if (array[previous] == a)
return previous;
return -1;
IG

}
int main()
{
R

int array[] = { 0, 33, 11, 52, 33, 15, 68, 63, 91,
32, 50, 99, 14, 23, 47, 60 };
Y

int a = 52;
int b = sizeof(array) / sizeof(array[0]);
P

// Find the index of 'a'


O

int index = JumpSearch(array, a, b);


C

// Print the index where 'a' is located


cout << "\nNumber " << a << " is at index " << index;
return 0;
}
The output of given C++ code is as follows:
/tmp/bItJRqfPru.o
Number 52 is at index 3

14
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

Some of the salient features of jump search are as follows:


zz Implemented in ordered arrays.
zz The ideal size of a block to be leaped is (√ n). Hence time complexity of Jump Search O(√ n).
zz Jump search is preferred in situations when the binary search is expensive. For instance in case,
when the value to be found is minimal.

13.3.4 Interpolation Search


Interpolation search enhancement over Binary Search in cases, when the elements in an ordered array

D
are consistently distributed. This search goes to multiple positions with respect to the search key.

E
To locate the relevant position, the formula being used is as follows:
//We need to retain larger value of pos.

V
// if the value to be found is nearer to ary[high],and

R
// lower value if nearer to ary[low]
pos = low + [ (x-ary[low])*( high - low) / (ary[high]-ary[low]) ]

E
ary[] ==> Array in which we need to search the value
x ==> data item to be found
S
E
low ==> Initial index in ary[]
high ==> Final index in ary[]
R
The derivation of the formula for Position is as follows:
Consider a linearly distributed or array.
T

The General equation of line : y = m*x + c.


H

Y refers to the element in the array and x is respective index.


Substituting the values of low, high and x in the equation:
IG

ary[high] = m*high+c ----(1)


ary[low] = m*low+c ----(2)
R

X = m*pos + c ----(3)
Y

M = (ary[high] – ary[low] )/ (high – low)


Subtracting equation (2) from (3):
P

X – ary[low] = m * (pos – low)


O

low + (x – ary[low])/m = pos


Pos = low + (x – ary[low]) *(high – low)/(ary[high] – ary[low])
C

The following C++ program is used to show implementation of interpolation search technique is as
follows:
#include<iostream>
using namespace std;
int interpolationSearch(int arr[], int Start, int end, int key) {
int dist, valRange, indexRange, estimate;
float fraction;

15
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

while(Start <= end && key >= arr[Start] && key <= arr[end]) {
dist = key - arr[Start];
valRange = arr[end] - arr[Start];
fraction = dist / valRange;
indexRange = end - Start;
estimate = Start + (fraction * indexRange);
if(arr[estimate] == key)
return estimate;
if(arr[estimate] < key)
Start = estimate +1;

D
else
end = estimate - 1;

E
}
return -1;

V
}
int main() {

R
int x, searchKey, location;
cout << "Enter number of items: ";

E
cin >> x;
int arr[x];
cout << "Enter items: " << endl;
S
E
for(int i = 0; i< x; i++) {
cin >> arr[i];
R
}
cout << "Enter search key to search in the list: ";
cin >> searchKey;
T

if((location = interpolationSearch(arr, 0, x-1, searchKey)) >= 0)


cout << "Item found at location: " << location << endl;
H

else
cout << "Item is not found in the list." << endl;
IG

}
The output of given C++ code is as follows:
/tmp/bItJRqfPru.o
R

Enter number of items: 5


Enter items:
Y

23 44 56 76 88
Enter search key to search in the list: 56
P

Item found at location: 2


O

13.4 LaB exercISe


C

13(a): Write a Program in C++ to implement Linear Search.


The following C++ program is used to show implementation of Linear Search algorithm is as follows:
#include<iostream>
using namespace std;
int main()
{

16
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

int array[7], i, num, index;


cout<<"Enter 7 Numbers: ";
for(i=0; i<7; i++)
cin>>array[i];
cout<<"\nEnter a Number to Search: ";
cin>>num;
for(i=0; i<7; i++)
{
if(array[i]==num)
{

D
index = i;
break;

E
}
}

V
cout<<"\nFound at Index No."<<index;
cout<<endl;

R
return 0;
}

E
The output of given C++ code is as follows:
/tmp/bItJRqfPru.o
Enter 7 Numbers: 1 2 3 4 5 6 7 S
E
Enter a Number to Search: 4
Found at Index No.3
R
13(b): Write a Program in C++ to implement binary search technique.
The following C++ program is used to show the implementation of the Binary Search Technique is as
T

follows:
H

#include <iostream>
using namespace std;
IG

int BinarySearch(int[], int, int, int);


int main()
{
R

int num[6] = {20, 52, 77, 30, 82, 108};


int search_num, location=-1;
cout<<"Enter the number that you want to search: ";
Y

cin>>search_num;
P

location = BinarySearch(num, 0, 6, search_num);


if(location != -1)
O

{
cout<<search_num<<" found in the array at the location: "<<location;
C

}
else
{
cout<<"Element not found";
}
return 0;
}
int BinarySearch(int a[], int First, int Last, int search_num)

17
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

{
int Middle;
if(Last >= First)
{
Middle = (First + Last)/2;
// to check whether the element exit in the middle location or not
if(a[Middle] == search_num)
{
return Middle+1;
}

D
else if(a[Middle] < search_num)
{

E
return BinarySearch(a,Middle+1,Last,search_num);
}

V
//Checking if the search element is exit in lower half
else

R
{
return BinarySearch(a,First,Middle-1,search_num);

E
}
}
return -1;
S
E
}
R
The output of given C++ code is as follows:
/tmp/bItJRqfPru.o
T

Enter the number that you want to search: 30


30 found in the array at the location: 4
H

Conclusion 13.5 cONcLUSION


IG

zz Searching is the process by which we try to find whether the required data exists in the given
structure or not.
R

zz Sorting is a task in which we arrange the given structure in a particular order: ascending order or
descending order.
Y

zz The Jump search approach is a new approach for searching a sorted array for a single element.
P

zz In insertion sort, an element is placed at its correct position by moving all the elements greater than
this element to its right.
O

zz In Radix sort, the numerical data is sorted in n passes, where n is the maximum number of digits in
the numerical data.
C

zz In Linear Search, each record of a file is searched, one at a time, until the desired data is found.
zz Binary Search is a search that uses the divide-and-conquer approach.
zz Jump Search is a searching algorithm applicable for ordered arrays.
zz Interpolation Search enhancement over Binary Search in cases, when the elements in an ordered
array are consistently distributed.

18
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

13.6 gLOSSary

zz Searching: the process by which we try to find whether the required data exists in the given structure
or not
zz Sorting: a task in which we arrange the given structure in a particular order, i.e., ascending order
or descending order
zz Jump search: an approach for searching a sorted array for a single element
Insertion sort: An element is placed at its correct position by moving all the elements greater than

D
zz
this element to its right

E
zz radix sort: The numerical data is sorted in n passes, where n is the maximum number of digits in
the numerical data is a radix sort

V
zz Linear search: In this search, each record of a file is searched, one at a time, until the desired data
is found

R
zz Binary search: a search which uses the divide-and-conquer approach

E
zz Jump search: a searching algorithm applicable for ordered arrays
Interpolation search: an enhancement over Binary Search in cases, when the elements in an ordered
zz
array are consistently distributed
S
E
13.7 SeLf-aSSeSSMeNT qUeSTIONS
R

a. Multiple choice questions


T

1. Which among the following is the process by which we try to find whether the required data exists
H

in the given structure or not?


a. Searching
IG

b. Sorting
c. Jump search
R

d. Interpolation search
2. It which task we arrange the given structure in a particular order?
Y

a. Insertion
P

b. Searching
O

c. Sorting
d. Radix
C

3. In which of the following, an element is placed at its correct position by moving all the elements
greater than this element to its right?
a. Radix sort
b. Insertion sort
c. Bubble sort
d. Merge sort

19
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

4. The average number of comparisons in the insertion sort is:


a. 0(n)
b. 0(n+1)
c. 0(n2)
d. (n)
5. Which of these is a technique used for a quick retrieval of the desired data from a large volume of
data.
a. Sorting

D
b. Searching

E
c. Jump search
d. Hashing

V
6. In which among the following each record of a file is searched, one at a time, until the desired data

R
is found?
a. Linear search

E
b. Binary search
c. Jump search
d. Interpolation search S
E
7. The Jump search approach is a new approach for searching a sorted array for a __________ element.
R
a. Multiple
b. Single
T

c. Finite
H

d. Infinite
8. When a linear search is unsuccessful, what will be its time complexity?
IG

a. (n)
b. 0(n+1)
R

c. 0(n+2)
d. 0(n)
Y

9. The worst case of time complexity in the binary search algorithm is _____________.
P

a. O(log2 n)
b. 0(log2)
O

c. 0(log n)
C

d. 0(n)
10. Which among the following uses the divide-and-conquer approach?
a. Searching
b. Hashing
c. Binary search
d. Sorting

20
UNIT 13: Sorting and Searching JGI JAIN
DEEMED-TO-BE UNIVERSITY

B. essay Type questions


1. Outline the concept of sorting and searching.
2. Explain the implementation of insertion sort.
3. On the basis of the technique used for locating the required data in a structure, the searching process
is divided into different types. Describe the term searching algorithm with its types.
4. Interpret the binary search in detail.
5. Define Radix Sort.

D
13.8 aNSwerS aNd hINTS fOr SeLf-aSSeSSMeNT qUeSTIONS

E
V
a. answers to Multiple choice questions

R
q. No. answer

E
1. a. Searching

2. c. Sorting

3. b. Insertion sort S
E
4. c. 0(n2)
R
5. d. Hashing

6. a. Linear search
T

7. b. Single
H

8. d. 0(n)
IG

9. a. O(log2 n)

10. c. Binary search


R

B. hints for essay Type questions


Y

1. Searching and sorting are the two most important tasks applied to data structures. Searching is the
process by which we try to find whether the required data exists in the given structure or not. Refer
P

to Section Introduction
O

2. In insertion sort, an element is placed at its correct position by moving all the elements greater than
this element to its right. Refer to Section Implementation of Sorting Technique
C

3. The process of searching for a particular data item in a data structure consists of comparison and
advancement operations. Refer to Section Searching Algorithms
4. Binary Search is a search that uses the divide-and-conquer approach. Refer to Section Searching
Algorithms
5. In Radix sort, the numerical data is sorted in n passes, where n is the maximum number of digits in
the numerical data. Refer to Section Implementation of Sorting Technique

21
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

@ 13.9 POST-UNIT readINg MaTerIaL

zz [Link]
UGI9DwAAQBAJ?hl=en&gbpv=1&dq=sorting+and+searching&printsec=frontcover
zz [Link]

13.10 TOPIcS fOr dIScUSSION fOrUMS

D
zz Discuss with your friends and classmates about the concept of searching and sorting and try to

E
explore the process of sorting and searching utilised in real world situations.

V
R
E
S
E
R
T
H
IG
R
Y
P
O
C

22
UNIT

14

D
E
Hashing

V
R
E
Names of Sub-Units
S
E
Hashing Table Organizations, Hashing: The Symbol Table, Hashing Functions, Static and Dynamic
R
Hashing, Collision-Resolution Techniques
T

Overview
H

This unit begins by discussing about the concept of hashing, hashing table organization. Next the unit
IG

discusses the Hashing: the symbol table. Further the unit explains the hashing functions and static
and dynamic hashing. Towards the end, the unit discusses the collision-resolution techniques.
R

Learning Objectives
Y
P

In this unit, you will learn to:


Explain the concept of hashing
O

a Describe the significance of hashing table organizations and hashing: the symbol table
C

a Discuss the hashing functions


a Assess the significance of static and dynamic hashing
a Explain the concept of collision-resolution techniques
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of hashing
a Determine the significance of hashing table organizations and hashing: the symbol table
a Explore the concept of hashing functions
Determine the significance of static and dynamic hashing

D
a

a Evaluate the importance of collision-resolution techniques

E
V
Pre-Unit Preparatory Material

R
a [Link]

E
14.1 INTrOdUcTION

S
Hashing is a technique used for a quick retrieval of the desired data from a large volume of data. This
scheme is used when a record is stored at a particular address and this address is to be computed by
E
applying a formula: hash function on the key, the primary key of the record. The hash function ( ) is used
R
in the following manner:
a=h(k)
In this equation, a is the address computed at the time of the application of the hash function on
T

the k key of the record. The hash function should be selected in such a way that it results in a unique
H

address, every time it is used. However, it is not practically feasible because there are frequent chances
of “collision” i.e. we may get the address of the record with the k1 key, where already a record with the
IG

k2 key is stored. These collided records are called synonyms and we apply certain collision resolution
techniques to resolve the conflict.
The domain of the hashing function is the interval of the key. If the keys are of 3 digits, we say the
R

domain of the hash function is (0,999). If the keys are of 5 digits, we say that domain of the hash function
is (0, 99999).
Y

The range of the hash function is the capacity of the storage, where the records are stored. If the array
P

where the records are stored consists of 1000 addresses, we say that the range of the hash function is
(0,999). The hash function should be chosen so that it distributes the keys uniformly over the range of
O

the storage. If the total capacity of the storage is n, then the good function should distribute the keys
over the range (0, n-1).
C

14.2 HaSH TabLe OrgaNIzaTION


Hash Table or Hash Map is a two-dimensional structure where the data (associated with some key) is
mapped or hashed to some value. Hash function is used to determine the value of a key. In addition, it is
used to transform the key into the address or the slot (bucket address) where the corresponding value
is to be sought.

2
UNIT 14: Hashing JGI JAIN
DEEMED-TO-BE UNIVERSITY

A hash table is a data structure that stores data in multiple places at the same time. The information
is kept in an array with unique indexes for each entry. Data retrieval can be quick after we understand
the index values of the various data fields. As the size of the data grows larger, the search and insertion
operations in data structures become exceedingly fast. Hash tables keep data in arrays and utilise the
hash technique to create an index that may be used to find or insert elements.

14.2.1 Linear Probing


As you know, we use a hashing technique to index an array that is already in use. You can use this to find

D
subsequent free addresses in the array by navigating to subsequent slots until you search for a free slot.
This process is called linear probing.

E
Some of the fundamental operations of linear probing are as follows:
Search: Find a data entry in a hash table

V
zz

zz Insert: Insert data item into hash table

R
zz delete: Hash table data item delete item

E
14.2.2 Hashing Method

S
There are several methods of hashing and each method has its own way of computing the hashing
E
address. The method which uniformly distributes the hashing addresses and leads to minimum collisions
is highly preferred. Following are the different methods of hashing:
R
zz Division method
zz Mid square method
T

zz Folding method
H

division Method
IG

This method is also called the divide and remainder method. Here, the key is divided by any number n
and the remainder is taken to be the address.
R

Hence, the hash function is: h(k)=k mod n


This method produces the addresses ranging from 0 to n-1. The value of n should be chosen carefully.
Y

If it is taken as the power of 10, say 100, then all the keys having identical last two digits certainly hash
into the same address. If n is chosen as an even integer, then all the even keys hash into odd addresses.
P

A good choice of n is any number, which is not divisible by 2, 3, 5, 10 or which is a prime number.
O

Mid Square Method


C

In this method, the key value is squared and a few digits are extracted from the middle of the squared
value. For example, if the hash address to be selected is of 3 digits and the key is 1234, then the square of
1234 is 1522756 and the middle value of 3 digits can be chosen as 227. This method produces the addresses
that are uniformly distributed over the range of the hashing function and if the keys are large enough,
then a selected part of the key can be squared.

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Folding Method
Suppose the hash address that needs to be generated is of d digits. Now, when we use this method, the
key is first divided into the groups of d digits, starting from the right. Then, these groups are added to
compute their sum. The last d digit of the sum is considered as the hash address. For example, suppose
the key is 12345678 and the hash address desired is of 3 digits. Then, from the right, the key 12345678 is
divided into the groups of 3 digits, beginning from the right. Thereafter, the three groups of digits are
added to make the sum as 1035, as shown in the following example:
12/345/678

D
Sum of 12+345+678 is 1035
The last three digits of the sum are considered as hash address i.e. 035 or 35 as are the hash address.

E
Hence, this method is considered to be flexible and can be modified as per our need.

V
14.2.3 Search Functionality

R
To find an element, we must compute the hash code of the key supplied and then store the element in
the array using the hash code as an index. If the element cannot be recognised using the computed hash

E
code, we can use linear probing to find it.

14.2.4 Insert Operation


S
E
To insert an element, we must first compute the hash code of the key provided, and then use the hash
code as an index to position the element in the array. Using linear probing for vacant regions, we can
R
discover the resulting hash code.
T

14.2.5 delete Operation


In order to delete an element, we need to compute ciphered hash of key value entered and place it through
H

ciphered hash as array index. By using linear probing, we can obtain the data item if it is not identified
by calculated ciphered hash. If it is located, reserve a counter fort value for managing execution of hash
IG

table.

14.3 HaSHINg: THe SyMbOL TabLe


R

A substantial information store generated and handled by a compiler is referred to as a symbol table. It
Y

stores information on the binding and scope of names and other items such as function names, classes,
variables, and objects.
P

During the syntactic and lexical analysis phases, a symbol table can be created.
O

Compilers take data during the analysis phase and generate code during the synthesis phase. It is used
to achieve time efficiency and is used in numerous phases of the compiler, as described below:
C

zz Lexical analysis: It creates a symbol table from the most recent table records.
zz Syntax analysis: Add details about the scope, attitude type, line of reference, and dimension in the
table.
zz Semantic analysis: Search semantics using the information in the table.
zz Intermediate code generation: Uses a symbol table to determine how and what type of run time is
allotted, as well as to add temporary variable data.

4
UNIT 14: Hashing JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz code optimization: For machine-dependent optimization, use the information in the symbol table.
zz Target code generation: Uses the identifier’s address information from the table to generate code.

14.3.1 Implementation of Symbol Table


Generally, two tables are managed in hashing scheme. Symbol table and hash table are the significant
technique to deploy symbol tables.
Hash table refers to the array having index spanning from 0 to Size Of Table-1. There cords directs to the

D
identities of symbol table. For looking up identities (names), one must utilize hash procedure which has
been resulted in integer between 0 to tablesize-1. Lookup and insertion rapid-O(1). Quick search can be

E
applied but hashing becomes complex to deploy.

V
14.4 HaSHINg FUNcTIONS

R
In cryptography, hash functions are the most often employed mathematical functions for establishing
security. A hash function converts an arbitrary-size input value to a fixed-size value. As a result, the

E
input can be any length, but the output is always the same length. Hash values or hashes are the outputs
generated.

S
Another important thing to remember is that Hash Functions and Cryptography are independent.
E
Encryption is a two-way function, which means that encrypted data can only be decrypted via a private
key, making it reversible. Hashing is a one-way function that is also known as hash functions (i.e., hashes
R
cannot be reversed). Hashing, as a result, outperforms cryptography.
Password verification is the most common application of hashing. When the user enters the password,
T

the hash is created and compared to the hash in the database. The user can log in if the hashes are the
same; otherwise, the user must re-enter the password.
H

The following are some of the most commonly used hashing functions:
IG

zz Md: It is referred to as Message Digest. MD2, MD4, MD5, and MD6 are all possibilities. MD is a Hash
function with a 128-bit value.
(SHa): It stands for Secure Hash Algorithm. It can be one of the following: SHA-0, SHA-1, SHA-2, or
R

zz
SHA-3. The SHA-2 family includes versions such as SHA-224, SHA-256, SHA-384, and SHA-512.
Y

zz rIPeMd: It stands for Race Integrity Primitives Evaluation Message Digest is the acronym for RACE
Integrity Primitives Evaluation Message Digest. Many people utilise RIPEMD, RIPEMD-128, and
P

RIPEMD-160. This method is also available in 256 and 320-bit versions.


O

zz Whirlpool: It is a modified variant of AES that uses a 512-bit hash function. Whirlpool comes in three
different versions: WHIRLPOOL-0, WHIRLPOOL-T, and WHIRLPOOL.
C

14.4.1 Properties of Hash Functions


To be efficient against numerous attacks from attackers, an ideal hash function should have the
following features. They are as follows:
zz resistance to Pre-Image
z The hash algorithm could not be reversed due to pre-image resistance.

5
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

z In other words, if any hash function “a” returns a hash value “c,” finding an input value “b” that
hashes to “c” should be extremely difficult.
z An attacker using a hash value seeking to find the input will be unable to do so because of this
property.
zz resistance to second pre –image
z Pre-image second to resistance, it should be extremely difficult to discover a different input that
generates the same hash value for any input and its hash value.
z To put it another way, if any hash function given an input “a” returns the hash value h(a), it

D
should be difficult to identify any other input value “b” for which h(b) = h(a) (a).
zz resistance to collision

E
z Collision resistance implies that finding two different inputs of any length that create the same
hash should be extremely difficult. Collision-free hash function is another name for this property.

V
This attribute protects against the well-known hash collision attack.

R
z Simply put, finding any two inputs x and y for a given hash function h is extremely difficult,
hence h(x) = h (y).

E
z This collision-free property ensures that collisions for a given hash function should be difficult
to find.
z S
This attribute also makes it difficult for an attacker to locate two input values that produce the
E
same hash.
R
Some of the application of hash function is commonly used in the following fields:
zz Authentication using Cryptocurrency Password Verification
T

zz Check for data and file integrity


Signature on a computer
H

zz

14.5 STaTIc aNd dyNaMIc HaSHINg


IG

Static hashing is a hashing technique that allows users to do lookups on a finished dictionary set (all
objects in the dictionary are final and not changing). Dynamic hashing, on the other hand, is a hashing
R

technique that creates and removes data buckets on demand.


Y

14.5.1 Static Hashing


P

Static hashing is a method of shortening a string of letters in computer programming in which the set
of shorter characters remains the same length to make data access quicker.
O

Address of output data bucket remains identical in static hashing. If you create address for stud_Id=13
through hashing procedure modulo(5), the output address is 3. It doesn’t modify the bucket location. The
C

count of information buckets remains same if static hashing is used.


Static hashing function is classified into two methods are as follows:
zz Open hashing: Rather than replacing the former one, the subsequent data cluster focused on
entering new record in the open hashing method. It is also called linear probing. For instance, A2 be
latest record that we need to add. The hash procedure creates address 222. It can be allocated at an

6
UNIT 14: Hashing JGI JAIN
DEEMED-TO-BE UNIVERSITY

alternative slot. The program focused on subsequent data bucket 501 followed by allocation of A2 to
the bucket, as shown in Figure 1:

Data Buckets

220
221
Data Record
222 222

D
A2 HASH
501

E
502
503

V
New Record © [Link] 504

R
E
Figure 1: Working of Open Hashing
zz
results will be associated after previous one. S
close hashing: Here, if we have occupied buckets, vacant bucket is given to identical hash and
E
Some of the commonly used static hash functions are as follows:
R
zz Insert: This command adds a new record to the hash table. The hash key will be used to construct an
address for that record.
T

zz delete: This action fetches the record to be destroyed before deleting the record’s address from
memory.
H

zz Update: The hash function first locates the record before updating it with new data.
Query: This method, also known as a search, uses the hash function to find entries that match
IG

zz
specified criteria.
R

14.5.2 dynamic Hashing


Dynamic hashing is a method of hashing, or decreasing a string of characters, in which the set of shorter
Y

characters grows, shrinks, and reorganises to fit the way data is retrieved in computer programming.
All things listed in an object dictionary become dynamic and may change when dynamic hashing is
P

employed.
O

This facilitates the process of removing and adding data buckets on the fly. The hash technique aids
in the development of a huge number of elements. Static hashing has the drawback of shrinking
C

dynamically as the database expands or shrinks. Extended hashing is another name for it. The hash
function produces a larger number of values.
Some of the commonly used dynamic hash functions are as follows:
zz Insertion: Calculates the bucket’s address. If the bucket is already full, new buckets can be added.
Furthermore, the hash function can be re-computed by adding additional bits to the hash value. It
is possible to add data to buckets that are not yet full.

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz Querying: Examines the hash index’s depth value and uses those bits to calculate the bucket address.
zz Update: This command run a query and updates the data.
zz delete: Executes a query to locate the data to be deleted.

14.6 cOLLISION-reSOLUTION TecHNIQUeS


Collision is said to occur when the hashing function produces the hash address (for a key), which is
already used by another key i.e. a key that already exists on that hash address. Such a situation is
not desirable and several methods are used to resolve collisions in this situation. There are two types

D
of collision resolution methods that resolve the problem which occurs on getting the same addresses
(synonyms) on the application of hash function on two different keys. These collision resolution methods

E
are:

V
zz Open addressing
zz Chaining

R
E
14.6.1 Open addressing
When the collision occurs, the synonym is placed at some other adjacent empty location in the hash table.

S
That is, no location outside the hash table is allocated for storing the key values. For example, consider
our hash table, which has the hash addresses in the range 0 to 100 and in this hash table, we want to
E
store the records of a few students. On applying the hash function on some roll number, say 312456,
R
we get the hash address as 36. However, we find that the location is already occupied by a record of
another student with roll number, say 302446 (so the situation of collision has occurred); and we cannot
store our record at this hash address. So, we look for an adjacent hash address in the Open Addressing
T

scheme to see if it is vacant to store the record of the student with the roll number 312456. This implies
that the hash address 37 is searched and if it is found vacant, the record is stored at this location; and if
H

it is also occupied with some student record, the next adjacent location (i.e. hash address 38) is searched
and so on. The Open Addressing method can be further divided into the following methods:
IG

zz Linear probing method: The simplest method to resolve a collision is to start with the hash address
(the location where the collision occurred) and do a sequential search for an empty location. Hence,
this method searches in a straight line, and it is therefore called linear probing. While applying this
R

method, the array should be considered as circular so that when the last location is reached, the
search proceeds to the first location of the array.
Y

The major drawback of linear probing is that, as the table becomes about half full, there is a
P

tendency towards clustering; that is, the records start to appear at continuous positions with small
gaps between them. Therefore, the sequential search needed to find an empty position, becomes
O

longer and longer. Hence, the performance of the hash table starts to degenerate.
The reason for clustering is the simple fact that on finding a collision, the increment added to
C

the hash address, to find the next vacant location, in the case of linear probing is ‘1’. To avoid this
problem of clustering, we should have different increment values every time to find the next empty
location. The solution is a method called rehashing ()where we use a second hash function. This
function generates an increment value, which is added to the hash address generated by the first
hash function (which generated the collision). This second hash address location is checked and if it
is vacant, the record is stored here; else again the second hash function is applied to generate some
other increment value until we get an empty location.

8
UNIT 14: Hashing JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Quadratic probing method: If there is a collision at the hash address h, then this method probes
the table at locations h+1, h+4, h+9,….., i.e., at locations h+i2 (%HASHSIZE) for i=1, 2, ….., that is, the
increment function is i2. This method reduces clustering and if the HASHSIZE is a power of 2, then
relatively few positions are probed.

14.6.2 chaining
Here, the synonym is linked with the help of pointers i.e. extra space outside the hash table is allocated
and connected in the form of a linked list.

D
Chaining method is used for the linked storage and hence, in this method, each slot of the hash table
has a pointer to the linked list and all the elements hashed to a slot are placed in the linked list attached

E
to that slot. For example, we can see in Figure 2 that all the elements hashed to slot 3 are placed in the
linked list attached to that slot. Similarly, the element hashed to slot 0 is linked to that slot with the help

V
of a pointer:

R
E
0 NULL

1
2
S
E
3 NULL
R
4
5
T



H



9
IG

NULL
R

Figure 2: Hash Table with pointers to the linked list


Linked storage has the following advantages:
Y

zz Space saving: When the hash table is maintained as a contiguous array, enough space has to be
P

set aside at the compilation time to avoid overflow. If the records themselves are in the hash table,
the empty positions (if there are many such positions) consume considerable space that might be
O

needed elsewhere. If, on the other hand, the hash table contains only pointers to the records, i.e. the
pointers that require only one word each, then the size of the hash table may be reduced to a large
C

extent.
zz collision resolution: It allows a simple and efficient way of collision handling. In this resolution, we
need to add only a link field to each record. Clustering is no problem at all, because the keys with
distinct hash addresses always go to distinct linked lists attached to distinct slots. In other words,
there are 10 linked lists and one linked list is attached to each slot of the hash table. The elements are
hashed to their respective slots and hence linked (in the form of a node) to the linked list attached to
that slot.

9
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz Overflow: A third advantage is that it is no longer necessary that the size of the hash table exceeds
the number of records. If there are more records than the entries in the table, then it means that
only some of the linked lists are now sure to contain more than one record. Even if the size of the
records is several times more than the size of the table, then the average length of the linked list
remains small and the sequential search on the appropriate list remains efficient.
zz deletion: Deletion becomes a quick and easy task in a chained hash table. For example, deletion of a
node from a linked list just requires the adjustment of address pointers.

The disadvantage of linked storage, however, is as follows:

D
zz The use of space: All the links require space. If the record is large, then this space is negligible in
comparison with the space needed for the records themselves; but if the records are small, then

E
it is not so. For instance, if we use the chaining method and make the hash table quite small with
the number of entries (n entries) equal to the number of items, then we use 3n words of storage

V
altogether: n for the hash table, n for the keys, and n for the links to find the next node on each chain.
Now, since the hash table is nearly full, the result is many collisions and several items in some of the

R
chains. Hence, searching gets a bit slow. On the other hand, suppose we use open addressing, then
putting the same 3n words of storage entirely into the hash table means that it is only one-third full;

E
and therefore, there are relatively few collisions and the search for any given item gets faster.

Conclusion 14.7 cONcLUSION S


E
zz Hashing is a technique used for a quick retrieval of the desired data from a large volume of data.
R
zz Hash Table or Hash Map is a two-dimensional structure where the data (associated with some key)
is mapped or hashed to some value.
T

zz A substantial information store generated and handled by a compiler is referred to as a symbol


table.
H

zz A hash function converts an arbitrary-size input value to a fixed-size value.


IG

zz Static hashing is a hashing technique that allows users to do lookups on a finished dictionary set (all
objects in the dictionary are final and not changing).
zz Dynamic hashing is a hashing technique that creates and removes data buckets on demand.
R

zz In open hashing the subsequent data cluster focused on entering new record in the open hashing
method.
Y

zz If we have occupied buckets, vacant bucket is given to identical hash and results will be associated
P

after previous one in close hashing.


Chaining method is used for the linked storage.
O

zz

14.8 gLOSSary
C

zz Hashing: This technique used for a quick retrieval of the desired data from a large volume of data
zz Hash table: It is also known as hash map and it is a two-dimensional structure where the data is
mapped or hashed to some value
zz Symbol table: A substantial information store generated and handled by a compiler is referred to
as a symbol table

10
UNIT 14: Hashing JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Hash function: It converts an arbitrary-size input value to a fixed-size value


zz Static hashing: It is a hashing technique that allows users to do lookups on a finished dictionary set
(all objects in the dictionary are final and not changing)
zz dynamic hashing: This hashing technique that creates and removes data buckets on demand
zz Opening hashing: In open hashing the subsequent data cluster focused on entering new record in
the open hashing method
zz close hashing: If we have occupied buckets, vacant bucket is given to identical hash and results will
be associated after previous one

D
zz chaining: This method is used for the linked storage

E
14.9 SeLF-aSSeSSMeNT QUeSTIONS

V
R
a. Multiple choice Questions

E
1. Which among the following is a technique used for a quick retrieval of the desired data from a large
volume of data?
a. Hashing
S
E
b. Collision
c. Functions
R
d. Hash table
2. Which of the following is a two-dimensional structure where the data (associated with some key) is
T

mapped or hashed to some value?


H

a. Hash function
b. Hash table
IG

c. Symbol table
d. Hash function
R

3. Which among the following is also called the divide and remainder method?
a. Folding method
Y

b. Mid square method


P

c. Division method
O

d. Hashing method
4. A substantial information store generated and handled by a compiler is referred to as which of the
C

following?
a. Hash table
b. Hash function
c. Hash map
d. Symbol table

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

5. In which of the following we must first compute the hash code of the key provided, and then use the
hash code as an index to position the element in the array?
a. Linear probing
b. Insert operation
c. Folding method
d. Deletion operation
6. Which of these creates a symbol table from the most recent table records?

D
a. Lexical analysis
b. Syntax analysis

E
c. Intermediate code generation

V
d. Code optimization

R
7. What does RIPEMD stands for?
a. Race Integrity Proper Evaluation Mail Digest

E
b. Race Internal Primitives Evaluation Message Digest

S
c. Race Integrity Primitives Evaluation Message Digest
E
d. Rapid Integrity Primitives Evaluation Message Digest
R
8. Which of the following is a hashing technique that creates and removes data buckets on demand?
a. Static hashing
T

b. Dynamic hashing
c. Open hashing
H

d. Closed hashing
IG

9. In which among the following hash function first locates the record before updating it with new
data?
R

a. Insert
b. Query
Y

c. Delete
P

d. Update
O

10. The method used for the linked storage is which of the following?
a. Hashing
C

b. Chaining
c. Open addressing
d. Quadratic probing method

12
UNIT 14: Hashing JGI JAIN
DEEMED-TO-BE UNIVERSITY

b. essay Type Questions


1. Explain the concept of hashing.
2. During the syntactic and lexical analysis phases, a symbol table can be created. Discuss
3. Hashing is a one-way function that is also known as hash functions. Describe the significance of
hashing functions.
4. Explain the concept of static and dynamic hashing.
5. When the collision occurs, the synonym is placed at some other adjacent empty location in the hash

D
table. Discuss

E
14.10 aNSWerS aNd HINTS FOr SeLF-aSSeSSMeNT QUeSTIONS

V
R
a. answers to Multiple choice Questions

E
Q. No. answer

1. a. Hashing
S
E
2. b. Hash table
R
3. c. Division method

4. d. Symbol table
T

5. b. Insert operation
H

6. a. Lexical analysis
IG

7. c. Race Integrity Primitives Evaluation Message Digest

8. b. Dynamic hashing
R

9. d. Update

10. b. Chaining
Y

b. Hints for essay Type Questions


P

1. Hashing is a technique used for a quick retrieval of the desired data from a large volume of data.
O

Refer to Section Introduction


2. A substantial information store generated and handled by a compiler is referred to as a symbol
C

table. Refer to Section Hashing: The Symbol Table


3. In cryptography, hash functions are the most often employed mathematical functions for
establishing security. Refer to Section Hashing Functions
4. Static hashing is a hashing technique that allows users to do lookups on a finished dictionary set
(all objects in the dictionary are final and not changing). Dynamic hashing, on the other hand, is a

13
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

hashing technique that creates and removes data buckets on demand. Refer to Section Static and
Dynamic Hashing
5. Collision is said to occur when the hashing function produces the hash address (for a key), which
is already used by another key i.e. a key that already exists on that hash address. Refer to Section
Collision Resolution Techniques

@ 14.11 POST-UNIT readINg MaTerIaL

D
zz [Link]
zz [Link]

E
pdf

V
14.12 TOPIcS FOr dIScUSSION FOrUMS

R
zz Discuss with your friends and classmates about the concept of hashing and their applications. Also,

E
discuss about the real world examples of hashing.

S
E
R
T
H
IG
R
Y
P
O
C

14
UNIT

15

D
E
Files and Files Organisation

V
R
E
Names of Sub-Units
S
E
Introduction, Data Hierarchy, File Attributes, Text Files, Binary Files, Basic File Operations, File
R
Organizations and Indexing
T

Overview
H

This unit begins by discussing about the concept of files and files organization and data hierarchy.
IG

Next, the unit discusses the files attributes, text files and binary files. Further the unit explains the
basic file operations. Towards the end, the unit discusses the file organizations and indexing.
R

Learning Objectives
Y
P

In this unit, you will learn to:


Discuss the concept of files and files organization
O

a Explain the concept of data hierarchy and files attributes


C

a Describe the text files and binary files


a Explain the significance of basic file operations
a Discuss the importance of file organizations and indexing
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


a Evaluate the concept of files and files organization
a Assess the concept of data hierarchy and files attributes
a Evaluate the importance of text files and binary files

D
a Determine the significance of basic file operations
a Assess the importance of file organizations and indexing

E
V
Pre-Unit Preparatory Material

R
[Link]

E
a

15.1 INTrOdUcTION S
E
File is a collection of record. It is allocated for storing large amount of information stored on devices
R
excluding internal memory of the computer. It meant that records are stored in the secondary storage.
The file should be organized so that operations will be determined effectively based on features of
secondary storage devices to deploy the file. Operations on file are to insert and delete records, update
T

or process records and search for records. These operations are applicable for lists, trees, arrays, list
structures and complex lists. Time used in managing information has been resulted in fast operations
H

and the efficiency should be determined against care needed to manage the organized data structure.
IG

At the time of executing high level language programs, the operations manage the files as data.
Operations are traversing and processing all records and also individuals chosen in random order.
Primary function of file system is to offer storage facilities and enable files to be searched conveniently
R

so that records may be sequentially retrieved.


Y

15.2 daTa HIerarcHy


P

Data hierarchy is the systematic organisation of data, which is typically done in a hierarchical method.
In data organisation, characters, fields, records, files, and so on are all used. This concept is a useful
O

place to start when trying to understand what makes up data and whether it has a structure. How can
someone decipher facts like ‘employee,’ ‘name,’ ‘department,’ ‘Marcy Smith,’ ‘Sales Department,’ and so
C

on, assuming they’re all connected? To help you understand these notions, think of them as smaller or
larger components in a hierarchy. Marcy Smith could be seen as a Sales Department employee or an
example of a Sales Department employee.

All data has its own hierarchy in data hierarchy, starting at a comprehensive top level and continuing
down to a definite bottom level. Someone, for example, is looking for a video game title in a database.

2
UNIT 15: Files and Files Organisation JGI JAIN
DEEMED-TO-BE UNIVERSITY

The video game console type is first, followed by the game creator, the genre, the first letter of the
game’s name, and lastly the game itself. This method of cataloguing data makes it easier to locate. It
also makes it easier for the database to process new data by ensuring that datum is only recorded in the
appropriate category.

15.2.1 components of data Hierarchy


The following are the components of data hierarchy:
zz Bits: In a computer, the smallest data item can have the value 0 or 1. A bit (short for “binary digit”—a

D
digit that can take one of two values) is a type of data item. Simple bit manipulations are performed
by computer circuitry, such as evaluating the value of a bit, altering the value of a bit, and reversing

E
the value of a bit (from 1 to 0 or from 0 to 1).

V
zz characters: Working with data in the low-level form of bits is inconvenient for programmers.
Instead, they prefer to operate with numbers (0–9), letters (A–Z and a–z), and special symbols (e.g.,

R
$, @, percent, &, *, (,), –, +, “,:,?, and /). Characters are made up of digits, letters, and special symbols.
The character set of a computer is the collection of all the characters that can be used to develop

E
programmes and represent data. Because computers can only handle 1s and 0s, the character set of
a computer depicts each character as a sequence of 1s and 0s. Unicode characters in Java are made

S
up of two bytes, each of which is eight bits long. The data type byte is available in Java and can be
E
used to represent byte data.
zz Fields: Fields are made up of characters or bytes. A field is a group of characters or bytes that
R
transmit data. A person’s name, for example, can be represented by a field of uppercase and
lowercase letters.
T

zz records and files: A record is a collection of interconnected fields. A file is a collection of interconnected
records. Any type of data in any format can be stored in a file. In different operating systems, a file
H

is viewed as a collection of bytes.


IG

zz record keys: At least one field in each record is chosen as a record key in order to retrieve specific
records from a file. A record key is a unique identifier for each record that identifies it as belonging
to a specific person or entity.
R

zz Sequential files: A file can be organised in a number of different ways. A sequential file is the most
popular, as it stores records in the order defined by the record-key field.
Y

zz database: A collection of related files is known as database and the collection of designed program
P

to create and manage database is known as database management system (DBMS).


O

15.3 FILe aTTrIBUTeS


C

A file can be a “free formed,” “indexed” or “organised” collection of linked bytes that is only understood
by the person who generated it. In other terms, a file is an item in a directory. Name, creator, date, type,
permissions and other information may be present in the file.

A file is a data structure that contains a series of records in a logical order. Files are kept in a file system,
which might be located on a drive or in main memory. Simple (plain text) or complicated files are both
possible (specially-formatted). The term “directory” refers to a group of files.

3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

The file system is a collection of directories organised at various levels as shown in Figure 1:

Data

Files

D
Directory

E
V
File System

R
E
Figure 1: Levels in File System
Some of the attributes of file system are as follows:
zz
S
Name: Every file has a name that is used to identify it in the file system. Two files with the same
E
name cannot exist in the same directory.
zz Identifier: Each file has its own extension that specifies the file’s kind in addition to its name. A text
R
file, for example, has the [Link], whereas a video file has the extension.mp4.
zz Type: Files are categorised into several sorts in a File System, such as video files, audio files, text files
T

and executable files.


Location: There are various areas in the File System where files can be stored. The location of each
H

zz
file is stored as an attribute.
IG

zz Size: One of the most essential characteristics of a file is its size. The number of bytes obtained by the
file in memory is referred to as the file’s size.
zz Protection: Distinct safeguards for different files may be desired by the computer’s administrator.
R

As a result, each file has its unique set of rights for each User group.
zz Time and date: Every file has a time stamp that includes the time and date when it was last changed.
Y
P

15.3.1 advanced File attributes


The permissions you can provide to folders and files are determined by how they are accessed. Because
O

they show in the advanced security settings dialogue box, these rights are referred to as “advanced”
permissions. To access them, go to the security tab of the Properties dialogue box and select the advanced
C

option.
The following is a list of advanced permissions for files and folders, along with a brief description of
each are as follows:
zz Traverse folder: This allows or disallows going through a restricted folder in the folder hierarchy
to access files and folders beneath the restricted folder. Only when the group or user is not granted
the “Bypass traverse checking user” right in the Group Policy snap-in does the traverse folder take
effect. This permission does not automatically grant access to programme files that can be run.

4
UNIT 15: Files and Files Organisation JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz execute file: This allows or disallows the execution of executable files.


zz List folder: This allows or disallows viewing of the folder’s file names and subfolder names. List
Folder affects just the contents of the folder; it has no bearing on whether or not the folder you are
setting the permission on will be listed.
zz read data: This allows or disallows viewing of data in files.
zz read attributes: This allows or disallows viewing of a file’s or folder’s properties, such as “read-only”
and “hidden”

D
zz read extended attributes: This allows or denies viewing the extended attributes of a file or folder.
Extended attributes are defined by programs and may vary by program.

E
zz create files: This allows or denies creating files within the folder
zz Write data: This allows or denies making changes to a file and overwriting existing content.

V
zz create folders: This allows or denies creating subfolders within the folder.

R
zz append data: It may consent or reject while creating changes to the end of the file but does not
change, deleting and overwriting when data is existing.

E
zz Write attributes: It allows or denies changing the attributes of a file or folder, for example, “readonly”
or “hidden”.
zz S
Write extended attributes: It allows or disallows modifying a file’s or folder's extended attributes.
E
Programs define extended characteristics, which might differ from one programme to the next. The
Write Extended Attributes permission does not grant the ability to create or delete files or folders;
R
rather, it grants the ability to modify the extended attributes of an existing file or folder.
zz delete subfolders and files: It allows or disallows the deletion of subfolders and files, even if the
T

delete permission on the subfolder or file has not been given.


delete: It allows or prevents the deletion of a file or folder. Even if you do not have Remove permission
H

zz
on a file or folder, if you have Delete Subfolders and Files permission on the parent folder, you may
still delete it.
IG

zz read permissions: This allows or denies reading permissions of a file or folder.


zz change permissions: This allows or denies changing permissions of the file or folder.
R

zz Take ownership: This allows or disallows the user to take ownership of a file or folder. Regardless of
any current rights that protect the file or folder, the owner of the file or folder can always alter its
Y

permissions.
P

zz Synchronise: This allows or disallows separate threads to synchronise with another thread that
may signal the handle for the file or folder. Only multithreaded, multiprocessing programs are
O

allowed to use this permission.


C

15.4 TexT FILeS


A text file is a form of digital file that is non-executable and only contains text. It can comprise numbers,
characters, symbols, and/or a combination of these, but not special formatting such as italic text, bold
text, underlined text, graphics, and so on. [Link] file extension is used to identify text files on a Microsoft
Windows computer. A given image is an example of a text file.
A text file, often known as an ASCII file or a flat file, is a type of file that is used to contain structured and
standard textual data or information that humans can read. The text file can be defined in a number of

5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

different formats, including ANSI for Windows-based operating systems and ASCII for cross-platform
use.
In a Windows OS, a text editor such as Word or Notepad is used to create a text file with the [Link]
(operating system). Nearly all computer languages, including PHP and Java, employ text files to write
and store source code. By changing the file extension [Link] [Link] [Link], the generated file can be
converted into a similar programming language.

15.5 BINary FILeS

D
A binary file includes all files that aren’t used to store textual material. A binary file can be used to
construct any custom file type as long as the essential information for reading the file is stored in the file.
Multiple types of data, such as images, video, and audio, are stored in the same file. The only stipulation

E
they make is that you have an application that can read this type of data from the system. The PNG file

V
format is an excellent example of the above-mentioned scenario. Most image viewers can read PNG files,
which contain graphical data. When you open a PNG file in a text editor, you’ll notice that the majority

R
of the file is made up of unrecognisable characters. However, there are readable text fragments strewn
over the file. This is due to the fact that the PNG file includes small portions for storing textual data in

E
addition to the graphical data. Other file formats may also enable this, which is possible due to binary
files’ dynamic nature.

S
A header appears at the top of binary files. The file’s key is this header. It’s used to keep track of the data
that identifies the file’s content. An example of binary file is shown in Figure 2:
E
R
T
H
IG
R
Y
P

Figure 2: Binary File


O

The first column has starting address of line when * represent repetition. Binary files has sequence of
bytes that represents the binary digits in eights. Binary files has bytes which are interpreted as symbol
or other characters. Example: compile computer programs which are sometimes referred as binaries.
C

These binary files contain sounds, images, compressed version of other files and any type of file content.
In computer program, binary files composed of blocks of metadata and headers to interpret data in file.
Header has magic numbers or signatures that will determine the format. GIF file has multiple images
and headers are used to define block of image data. If binary file do not have headers, it can be called
as flat binary file.
In order to binary files over some systems which do not enable all data values , they will be converted
into plain text. Encoding the data has demerits of enhancing the file size at the time of transfer and need

6
UNIT 15: Files and Files Organisation JGI JAIN
DEEMED-TO-BE UNIVERSITY

translation into binary. An enhanced size will be determined by low level link compression and text data
have less entropy as it has enhanced size.
The standard libraries and Microsoft windows enables the programmer to determine parameter if
file is focused on binary or plain text while opening a file. In Unix, the standard libraries enables the
programmer to determine whether a file is expected to be binary or text.

Viewing
Hex viewer is used to view file data as sequence of hexadecimal values of binary file. If the binary file is

D
viewed in text editor, each group will be translated as a character and user shows textual characters.
If the file is opened in other applications, then it has own use for each byte. The application considers
each byte as output stream of numbers between 0 and 255. It replaces the unprintable characters with

E
spaces indicating human readable text. It can be helpful for monitoring binary file to identify password

V
in games and hidden text and retain corrupted document. It can be used to explore the suspicious files
for unwanted effects. If the file is considered as run and executable, the operating system will interpret

R
the file as sequence of instructions in machine language.

E
Interpretation

S
Standards are significant to the binary files. ASCII character will be displayed in text. Byte may be pixel
or sound or entire word. Binary is meaningless until the executed algorithm describes what needs to be
E
done with each byte, word or bit. Evaluating the binary to map against the known formats will cause
wrong conclusion. It can be used in steganography where the binary file exhibits the hidden content.
R

15.6 BaSIc FILe OPeraTIONS


T

A file is a collection of logically related data stored on secondary storage in the form of a sequence
of operations. The creator of the file determines the content of the file. The many actions that can be
H

performed on a file, such as read, write, open, and close, are referred to as file operations. The user
performs these tasks with the assistance of the operating system’s commands. Some examples of
IG

common operations are as follows:


zz create operation: This action is performed to create a file in the file system. On the file system, it is
the most widely used operation. The linked application programme uses the file system to create a
R

new file of a certain type. This file system allocates space to the file. This new file gets placed in the
correct directory because the file system recognises the directory structure’s format.
Y

zz Open operation: This is the most typical operation that is done on the file. Before executing any file
processing actions, the file must first be opened. When a user wants to open a file, he or she specifies
P

a file name that will open that file in the file system. It instructs the operating system to use the open
O

system function and provides the file system with the file name.
zz Write operation: Using this method, the information is written into a file. A system call write specifies
C

the name of the file and the length of data to be written to it. After the last byte is written, the file
length is increased by a certain amount and the file pointer is shifted.
zz read operation: The contents of a file are read with this operation. The OS keeps a Read pointer
those points to the spot where the data has been read up to.
zz re-position or seek operation: The seek system call advances the file pointers forward or backward
in the file, depending on the user’s demands. This technique is typically done out with the help of file
management systems that provide direct access to files.

7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

zz delete operation: Not only will removing the file delete all of the data it contains, but it will also free
up disc space. To delete the selected file, the directory is searched. Once the directory entry is found,
all associated file space and the directory entry are released.
zz close operation: When the file has been processed, it should be closed so that all of the changes are
permanent and all of the resources used are released. When you close the file, it deallocates all of the
internal descriptors that were created when you opened it.

15.7 FILe OrgaNIzaTION aNd INdexINg

D
A file organization guarantees that records are prepared for processing. It’s used to discover out how to
efficiently organise each base relation’s files.

E
For example, let’s say we wish to sort employee information alphabetically by name. Sorting files by
employee name is a good way to organise them. A file organised by employee name, on the other hand,

V
isn’t the ideal way to find all employees having grades in a certain range.

R
The file organization can be classified into three types:
Sequential access file organization

E
zz

zz Direct access file organization


zz Indexed sequential access file organization
S
E
15.7.1 Indexing
R
Indexing is a data structure technique that helps to speed up data retrieval. As we can quickly locate
and access the data in the database, it is a must-know data structure that will be needed for database
optimizing. Indexing minimizes the number of disk accesses required when a query is processed. Indexes
T

are created as a combination of the two columns.


H

Data retrieval is aided by indexing, which is a data structure approach. Because it lets us to quickly
identify and access data in the database, it is a must-know data structure for database optimization.
IG

Indexing lowers the number of disc accesses necessary when a query is run. The two columns are mixed
together in indexes:
First column: The Search key is in the first column. It has a copy of the table’s primary key or
R

zz
candidate key. This column’s values can be sorted or not. However, if the values are sorted, the
related data is easily accessible.
Y

zz Second column: The Data reference or Pointer is the second column. It contains the disc block
P

address where the relevant key value can be found. Figure 3 depicts the structure of index:
O

Search Key Data Reference


C

Figure 3: Structure of Index

15.7.2 Types of Indexing


Indexing is classified into four types are as follows:
zz Primary indexing
zz Secondary indexing

8
UNIT 15: Files and Files Organisation JGI JAIN
DEEMED-TO-BE UNIVERSITY

zz Clustered indexing
zz Multilevel indexing

Primary Indexing
There are only two columns in primary indexing. The main key values, which are the search keys, are
in the first column. The pointers in the second column contain the address to the search key value’s
matching data block. The table should be sorted, and the records in the index file and the data blocks
should have a one-to-one relationship. This is a slower but more traditional mechanism. Primary

D
indexing is further classified into two types are as follows:
zz dense index: For each search key value in the data file, there is an index record that contains a

E
search key and a pointer. Despite the fact that the dense index is a quick solution, it requires more
memory to store index records for each key value. Figure 4 depicts dense index:

V
R
1 1 John 25
2 2 Jack 24

E
3 3 Amey 18
4 4 Ellena 29
5 5
S Kate 31
E
6 6 Will 26
Index record Data block
R

Figure 4: dense Index


T

zz Sparse index: There are only a few index records that point to the search key value. First, the index
record starts searching sequentially by pointing to a location of a value in the data file until it finds
H

the actual location of the search key value. Though sparse indexing is time-consuming, it requires
less memory to store index records as it has less of them. Figure 5 depicts sparse index:
IG

1 John 25
R

2 Jack 24
1
Y

3 Amey 18
4
4 Ellena 29
P

6
5 Kate 31
O

6 Will 26
C

Index record Data block

Figure 5: Sparse Index

Secondary Indexing (Non-clustered Indexing)


In the secondary indexing the columns of the candidate key hold the values with the respective pointer
that has the values to the location of an address.

9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

An intermediate node is a communication medium between index and data, as shown in Figure 6:

2 Jack 24

1 1 John 25
2 2
6 Will 26
3 4
3 Amey 18

D
4 5

5 6 4 Ellena 29

E
6 5 Kate 31

V
Index file Intermediate note Data block

R
Figure 6: Secondary Indexing

E
clustered Indexing
S
In clustered indexing the table is well-organized. When the indexes are created with the help of non-
E
primary key at that time, to get the unique values we associate more than two columns together to
identify data uniquely to create the index, as shown in Figure 7:
R
T

Sub_id Pointer 1 John 25

4 1 Mill 19
H

2 1 Gim 20
IG

4 4 Ellena 29
R

5 4 Ronald 19

6
Y

6 Will 26
P

6 Ruby 22
O

Index file Clustered data file


C

Figure 7: clustered Indexing

Multilevel Indexing
Multilevel indexing is used when the primary index does not fit in the memory. The indices are increased
when the size of the database is increased. In fact only a single-level index can be too huge to accumulate
in the main memory. The data block gets breaken down into the smaller blocks to be stored in the main
memory in multilevel indexing.

10
UNIT 15: Files and Files Organisation JGI JAIN
DEEMED-TO-BE UNIVERSITY

The multilevel indexing is further classified into two methods:


zz B+ tree indexing
zz B- tree indexing

Conclusion 15.8 cONcLUSION

zz Data hierarchy is the systematic organisation of data, which is typically done in a hierarchical
method.

D
zz A file can be a “free formed,” “indexed” or “organised” collection of linked bytes that is only understood
by the person who generated it.

E
zz A text file is a form of digital file that is non-executable and only contains text.

V
zz A file organization guarantees that records are prepared for processing.
zz Indexing is a data structure technique that helps to speed up data retrieval.

R
zz In the secondary indexing the columns of the candidate key hold the values with the respective
pointer that has the values to the location of an address.

E
zz There are only two columns in primary indexing.
zz In clustered indexing the table is well-organized.
S
E
zz Multilevel indexing is used when the primary index does not fit in the memory.
R
15.9 gLOSSary
T

zz data hierarchy: The systematic organisation of data, which is typically done in a hierarchical
method.
H

zz File: It can be a “free formed,” “indexed” or “organised” collection of linked bytes that is only
understood by the person who generated it.
IG

zz Text file: It is a form of digital file that is non-executable and only contains text.
zz File organization: The guarantees that records are prepared for processing in file organization.
R

zz Indexing: It is a data structure technique that helps to speed up data retrieval.


Secondary indexing: The columns of the candidate key hold the values with the respective pointer
Y

zz
that has the values to the location of an address.
P

zz clustered indexing: The table is well-organized in clustered indexing.


O

zz Multilevel indexing: It is used when the primary index does not fit in the memory.
C

15.10 SeLF-aSSeSSMeNT QUeSTIONS

a. Multiple choice Questions


1. Which of these is a collection of record?
a. File b. Table
c. Database d. Memory

11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

2. Which of the following is the systematic organisation of data, which is typically done in a hierarchical
method.
a. Files
b. Data hierarchy
c. Indexing
d. File attributes
3. Which among the following files are categorised into several sorts in a file system?
a. Name

D
b. Identifier

E
c. Type
d. Size

V
4. It allows or disallows viewing of the folder’s file names and subfolder names, it is which of the

R
following.
a. Traverse folder

E
b. Execute file
c. Create folder
d. List folder S
E
5. Which of the following extension is used to identify text files on a Microsoft Windows computer?
R
a. .txt
b. .php
T

c. .cpp
H

d. .org
6. Which among the following does not store textual file?
IG

a. Text file
b. Binary file
R

c. File organization
d. Index
Y

7. Which of the following are made up of characters or bytes?


P

a. Database
b. Bits
O

c. Characters
C

d. Fields
8. In which among the following for each search key value in the data file, there is an index record that
contains a search key and a pointer?
a. Primary indexing
b. Secondary indexing
c. Dense indexing
d. Multilevel indexing

12
UNIT 15: Files and Files Organisation JGI JAIN
DEEMED-TO-BE UNIVERSITY

9. A text file is also known as which of the following?


a. Flat file
b. Digital file
c. Sequential file
d. Execute file
10. Which of these is also considered as non-text file?
a. Sequential file

D
b. Binary file
c. Execute file

E
d. Flat file

V
B. essay Type Questions

R
1. Describe the concept of file.
2. All data has its own hierarchy in data hierarchy. Discuss

E
3. A text file, often known as an ASCII file or a flat file. Explain the significance of text file.
4. Describe the significance of binary file.
S
E
5. Indexing minimizes the number of disk accesses required when a query is processed. What is the
concept of indexing?
R

15.11 aNSWerS aNd HINTS FOr SeLF-aSSeSSMeNT QUeSTIONS


T
H

a. answers to Multiple choice Questions


IG

Q. No. answer

1. a. File
R

2. b. Data hierarchy
Y

3. c. Type
P

4. d. List folder
O

5. a. .txt

6. b. Binary file
C

7. d. Fields

8. c. Dense indexing

9. a. Flat file

10. b. Binary file

13
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms

B. Hints for essay Type Questions


1. File is a collection of record. It is allocated for storing large amount of information stored on devices
excluding internal memory of the computer. Refer to Section Introduction
2. Data hierarchy is the systematic organisation of data, which is typically done in a hierarchical
method. Refer to Section Data Hierarchy
3. A text file is a form of digital file that is non-executable and only contains text. It can comprise
numbers, characters, symbols, and/or a combination of these, but not special formatting such as
italic text, bold text, underlined text, graphics, and so on. Refer to Section Text Files

D
4. A binary file includes all files that aren’t used to store textual material. A binary file can be used to
construct any custom file type as long as the essential information for reading the file is stored in

E
the file. Refer to Section Binary Files
5. Indexing is a data structure technique that helps to speed up data retrieval. As we can quickly

V
locate and access the data in the database, it is a must-know data structure that will be needed for

R
database optimizing. Refer to Section File Organization and Indexing

E
@ 15.12 POST-UNIT readINg MaTerIaL

zz
S
[Link]
E
zz [Link]
R

15.13 TOPIcS FOr dIScUSSION FOrUMS


T

zz You can discuss about the concept of files and files organization with your friends. Also, discuss
about the concept of data hierarchy in real life.
H
IG
R
Y
P
O
C

14

You might also like