DATA STRUCTURE
Dr. Ashfaq Ahmad Najar
Assistant Professor G1, SCOPE
VIT Bhopal University
INTRODUCTION
• Data Structure can be defined as the group of data elements which provides an
efficient way of storing and organising data in the computer so that it can be used
efficiently.
• Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc.
• Data Structures are widely used in almost every aspect of Computer Science i.e.
Operating System, Compiler Design, Artificial intelligence, Graphics and many
more.
• Data Structures are the main part of many computer science algorithms as they
enable the programmers to handle the data in an efficient way.
• It plays a vital role in enhancing the performance of a software or a program as
the main function of the software is to store and retrieve the user's data as fast
as possible
Basic Terminology
■ Data structures are the building blocks of any program or the software.
■ Choosing the appropriate data structure for a program is the most difficult task for a
programmer.
Following terminology is used as far as data structures are concerned
■ Data: Data can be defined as an elementary value or the collection of values, for
example, student's name and its id are the data about the student.
■ Group Items: Data items which have subordinate data items are called Group item,
for example, name of a student can have first name and the last name.
■ Record: Record can be defined as the collection of various data items, for example,
if we talk about the student entity, then its name, address, course and marks can be
grouped together to form the record for the student.
■ File: A File is a collection of various records of one type of entity, for example, if there
are 60 employees in the class, then there will be 20 records in the related file where
each record contains the data about each employee.
■ Attribute and Entity: An entity represents the class of certain objects. it contains
various attributes. Each attribute represents the particular property of that entity.
■ Field: Field is a single elementary unit of information representing the attribute of an
entity.
Need of Data Structures
As applications are getting complexed and amount of data is increasing day by day,
there may arise the following problems:
■ Processor speed: To handle very large amount of data, high speed processing is
required, but as the data is growing day by day to the billions of files per entity,
processor may fail to deal with that much amount of data.
■ Data Search: Consider an inventory size of 106 items in a store, If our application
needs to search for a particular item, it needs to traverse 106 items every time,
results in slowing down the search process.
■ Multiple requests: If thousands of users are searching the data simultaneously on a
web server, then there are the chances that a very large server can be failed during
that process
In order to solve the above problems, data structures are used. Data is organized to
form a data structure in such a way that all items are not required to be searched and
required data can be searched instantly.
Advantages of Data Structures
Efficiency:
■ Efficiency of a program depends upon the choice of data structures.
■ For example: suppose, we have some data and we need to perform the search for a
perticular record.
■ In that case, if we organize our data in an array, we will have to search sequentially
element by element.
■ hence, using array may not be very efficient here.
■ There are better data structures which can make the search process efficient like
ordered array, binary search tree or hash tables.
Reusability:
■ Data structures are reusable, i.e. once we have implemented a particular data
structure, we can use it at any other place.
■ Implementation of data structures can be compiled into libraries which can be used
by different clients.
Abstraction:
■ Data structure is specified by the ADT which provides a level of abstraction.
■ The client program uses the data structure through interface only, without getting
into the implementation details.
Data Structure Classification
Primitive Data Structure
■ Primitive data types are the data types available in most of the programming
languages.
■ These data types are used to represent single value.
■ It is a basic data type available in most of the programming language.
Data type Description
Integer Used to represent a number without decimal point.
Float Used to represent a number with decimal point.
Character Used to represent single character.
Boolean Used to represent logical values either true or false.
Non-Primitive Data Structure
■ Data type derived from primary data types are known as Non-Primitive data types.
■ Non-Primitive data types are used to store group of values.
■ It can be divided into two types:
1. Linear Data Structure
2. Non-Linear Data Structure
Linear Data Structures:
■ A data structure is called linear if all of its elements are arranged in the linear order.
■ In linear data structures, the elements are stored in non-hierarchical way where each
element has the successors and predecessors except the first and last element.
■ Types of Linear Data Structures are given below:
Arrays:
■ An array is a collection of similar type of data items and each data item is called an
element of the array.
■ The data type of the element may be any valid data type like char, int, float or double.
■ The elements of array share the same variable name but each one carries a different
index number known as subscript.
■ The array can be one dimensional, two dimensional or multidimensional.
■ The individual elements of the array age are:
age[0], age[1], age[2], age[3],......... age[98], age[99].
Linked List:
■ Linked list is a linear data structure which is used to maintain a list in the memory.
■ It can be seen as the collection of nodes stored at non-contiguous memory
locations.
■ Each node of the list contains a pointer to its adjacent node.
Stack:
■ Stack is a linear list in which insertion and deletions are allowed only at one end,
called top.
■ A stack is an abstract data type (ADT), can be implemented in most of the
programming languages.
■ It is named as stack because it behaves like a real-world stack, for example: - piles
of plates or deck of cards etc.
Queue:
■ Queue is a linear list in which elements can be inserted only at one end called rear
and deleted only at the other end called front.
■ It is an abstract data structure, similar to stack.
■ Queue is opened at both end therefore it follows First-In-First-Out (FIFO) methodology
for storing the data items.
Non Linear Data Structures:
■ This data structure does not form a sequence i.e. each item or element is connected
with two or more other items in a non-linear arrangement.
■ The data elements are not arranged in sequential structure.
■ Types of Non Linear Data Structures are given below:
Trees:
■ Trees are multilevel data structures with a hierarchical relationship among its
elements known as nodes.
■ The bottommost nodes in the hierarchy are called leaf node while the topmost node
is called root node.
■ Each node contains pointers to point adjacent nodes.
■ Tree data structure is based on the parent-child relationship among the nodes.
■ Each node in the tree can have more than one children except the leaf nodes
whereas each node can have at most one parent except the root node.
Graphs:
■ Graphs can be defined as the pictorial representation of the set of elements
(represented by vertices) connected by the links known as edges.
■ A graph is different from tree in the sense that a graph can have cycle while the tree
can not have the one.
Operations on data structure
Traversing:
■ Every data structure contains the set of data elements.
■ Traversing the data structure means visiting each element of the data structure in
order to perform some specific operation like searching or sorting.
■ Example: If we need to calculate the average of the marks obtained by a student in
6 different subject, we need to traverse the complete array of marks and calculate
the total sum, then we will divide that sum by the number of subjects i.e. 6, in order
to find the average.
Insertion:
■ Insertion can be defined as the process of adding the elements to the data structure
at any location.
■ If the size of data structure is n then we can only insert n-1 data elements into it.
Deletion:
■ The process of removing an element from the data structure is called Deletion.
■ We can delete an element from the data structure at any random location.
■ If we try to delete an element from an empty data structure then underflow occurs.
Searching:
■ The process of finding the location of an element within the data structure is called
Searching.
■ There are two algorithms to perform searching, Linear Search and Binary Search.
We will discuss each one of them later in this tutorial.
Sorting:
■ The process of arranging the data structure in a specific order is known as Sorting.
■ There are many algorithms that can be used to perform sorting, for example,
insertion sort, selection sort, bubble sort, etc.
Merging:
■ When two lists List A and List B of size M and N respectively, of similar type of
elements, clubbed or joined to produce the third list, List C of size (M+N), then this
process is called merging
DS ALGORITHM
Abstract Data type (ADT)
■ ADT stands for Abstract Data Type.
■ It is an abstraction of a data structure.
■ Abstract data type is a mathematical model of a data structure.
■ It describes a container which holds a finite number of objects where the objects
may be associated through a given binary relationship.
■ It is a logical description of how we view the data and the operations allowed without
regard to how they will be implemented.
■ ADT concerns only with what the data is representing and not with how it will
eventually be constructed.
■ It is a set of objects and operations. For example, List, Insert, Delete, Search, Sort.
■ It consists of following three parts:
1. Data
2. Operation
3. Error
1. Data describes the structure of the data used in the ADT.
2. Operation describes valid operations for the ADT. It describes its interface.
3. Error describes how to deal with the errors that can occur.
Advantages of ADT
■ ADT is reusable and ensures robust data structure.
■ It reduces coding efforts.
■ Encapsulation ensures that data cannot be corrupted.
■ ADT is based on principles of Object Oriented Programming (OOP) and Software
Engineering (SE).
■ It specifies error conditions associated with operations.
Sparse Matrix
■ A matrix is a two-dimensional data object made of m rows and n columns, therefore
having total m x n values.
■ If most of the elements of the matrix have 0 value, then it is called a sparse matrix.
Why to use Sparse Matrix instead of simple matrix ?
■ Storage: There are lesser non-zero elements than zeros and thus lesser memory can
be used to store only those elements.
■ Computing time: Computing time can be saved by logically designing a data
structure traversing only non-zero elements..
■ Example:
00304
00570
00000
02600
■ Representing a sparse matrix by a 2D array leads to wastage of lots of memory as
zeroes in the matrix are of no use in most of the cases.
■ So, instead of storing zeroes with non-zero elements, we only store non-zero
elements. This means storing non-zero elements with triples- (Row, Column, value).
■ Sparse Matrix Representations can be done in many ways following are two common
representations:
■ Array representation
■ Linked list representation
Method 1: Using Arrays
2D array is used to represent a sparse matrix in which there are three rows named as
■ Row: Index of row, where non-zero element is located
■ Column: Index of column, where non-zero element is located
■ Value: Value of the non zero element located at index – (row,column)
#include <stdio.h>
#define MAX 20
void read_matrix(int a[10][10], int row, int column);
void print_sparse(int b[MAX][3]);
void create_sparse(int a[10][10], int row, int column, int b[MAX][3]);
int main()
{
int a[10][10], b[MAX][3], row, column;
printf("\nEnter the size of matrix (rows, columns): ");
scanf("%d%d", &row, &column);
read_matrix(a, row, column);
create_sparse(a, row, column, b);
print_sparse(b);
return 0;
}
void read_matrix(int a[10][10], int row, int column)
{
int i, j;
printf("\nEnter elements of matrix\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
printf("[%d][%d]: ", i, j);
scanf("%d", &a[i][j]);
}
}
}
void create_sparse(int a[10][10], int row, int column, int b[MAX][3])
{
int i, j, k;
k = 1; // to track non zero entries
b[0][0] = row; if (a[i][j] != 0) //Scans all a[i][j], and if value ≠ 0,
b[0][1] = column; {
b[k][0] = i;
for (i = 0; i < row; i++)
b[k][1] = j;
{
b[k][2] = a[i][j];
for (j = 0; j < column; j++)
k++;
{
}
}
b[0][2] = k - 1;
}
}
void print_sparse(int b[MAX][3])
{
int i, column;
column = b[0][2];
printf("\nSparse form - list of 3 triples\n\n");
for (i = 0; i <= column; i++)
{
printf("%d\t%d\t%d\n", b[i][0], b[i][1], b[i][2]);
}
}
Enter the size of matrix (rows, columns): 3 4
Enter elements of matrix
[0][0]: 6
[0][1]: 0
[0][2]: 0
[0][3]: 0
[1][0]: 0
[1][1]: 1
[1][2]: 0
[1][3]: 0
[2][0]: 0
[2][1]: 0
[2][2]: 0
[2][3]: 5
Sparse form - list of 3 triples
3 4 3
0 0 6
1 1 1
2 3 5
Method 2: Using Linked Lists
In linked list, each node has four fields. These four fields are defined as:
■ Row: Index of row, where non-zero element is located
■ Column: Index of column, where non-zero element is located
■ Value: Value of the non zero element located at index – (row,column)
■ Next node: Address of the next node
LINKED LIST
■ Before understanding the linked list concept, we first look at why there is a need for
a linked list.
■ If we want to store the value in a memory, we need a memory manager that
manages the memory for every variable.
■ For example, if we want to create a variable of integer type like:
■ int x;
■ In the above example, we have created a variable 'x' of type integer.
■ As we know that integer variable occupies 4 bytes, so 'x' variable will occupy 4 bytes
to store the value.
■ Suppose we want to create an array of integer type like:
■ int x[3];
■ In the above example, we have declared an array of size 3.
■ As we know, that all the values of an array are stored in a continuous manner, so all
the three values of an array are stored in a sequential fashion.
■ The total memory space occupied by the array would be 3*4 = 12 bytes.
There are two major drawbacks of using array:
■ We cannot insert more than 3 elements in the above example because only 3
spaces are allocated for 3 elements.
■ In the case of an array, lots of wastage of memory can occur. For example, if we
declare an array of 50 size but we insert only 10 elements in an array. So, in this
case, the memory space for other 40 elements will get wasted and cannot be used
by another variable as this whole space is occupied by an array.
In array, we are providing the fixed-size at the compile-time, due to which wastage of
memory occurs. The solution to this problem is to use the linked list.
What is Linked List?
■ A linked list is also a collection of elements, but the elements are not stored in a
consecutive location.
■ Suppose a programmer made a request for storing the integer value then size of 4-byte
memory block is assigned to the integer value.
■ The programmer made another request for storing 3 more integer elements; then, three
different memory blocks are assigned to these three elements but the memory blocks are
available in a random location.
■ So, how are the elements connected?.
■ These elements are linked to each other by providing one additional information along
with an element, i.e., the address of the next element.
■ The variable that stores the address of the next element is known as a pointer.
■ Therefore, we conclude that the linked list contains two parts, i.e., the first one is the data
element, and the other is the pointer.
■ The pointer variable will occupy 4 bytes which is pointing to the next element.
■ A linked list can also be defined as the collection of the nodes in which one node is
connected to another node, and node consists of two parts, i.e., one is the data part
and the second one is the address part, as shown in the below figure:
■ In the above figure, we can observe that each node contains the data and the
address of the next node. The last node of the linked list contains the NULL value in
the address part.
How can we declare the Linked list?
■ The declaration of an array is very simple as it is of single type.
■ But the linked list contains two parts, which are of two different types, i.e., one is a
simple variable, and the second one is a pointer variable.
■ We can declare the linked list by using the user-defined data type known as structure.
■ The structure of a linked list can be defined as:
struct node Self Referential Structure: contains a pointer to a
Structure of the same type.
{
Use for creating a node of the SLL.
int data;
struct node *next;
}
■ In the above declaration, we have defined a structure named as a node consisting of two
variables: an integer variable (data), and the other one is the pointer (next), which
contains the address of the next node.
Advantages of using a Linked list over
Array
The following are the advantages of using a linked list over an array:
■ Dynamic data structure:
The size of the linked list is not fixed as it can vary according to our requirements.
■ Insertion and Deletion:
Insertion and deletion in linked list are easier than array as the elements in an array are stored in a
consecutive location.
In contrast, in the case of a linked list, the elements are stored in a random location.
The complexity for insertion and deletion of elements from the beginning is O(1) in the linked list, while in
the case of an array, the complexity would be O(n).
If we want to insert or delete the element in an array, then we need to shift the elements for creating the
space.
On the other hand, in the linked list, we do not have to shift the elements. In the linked list, we just need
to update the address of the pointer in the node.
■ Memory efficient
Its memory consumption is efficient as the size of the linked list can grow or shrink
according to our requirements.
■ Implementation
Both the stacks and queues can be implemented using a linked list.
Disadvantages of Linked list
The following are the disadvantages of linked list:
■ Memory usage
The node in a linked list occupies more memory than array as each node occupies
two types of variables, i.e., one is a simple variable, and another is a pointer variable
that occupies 4 bytes in the memory.
■ Traversal
In a linked list, the traversal is not easy.
If we want to access the element in a linked list, we cannot access the element
randomly, but in the case of an array, we can randomly access the element by index.
For example, if we want to access the 3rd node, then we need to traverse all the
nodes before it.
So, the time required to access a particular node is large.
■ Reverse traversing
In a linked list, backtracking or reverse traversing is difficult. In a doubly linked list, it
is easier but requires more memory to store the back pointer.