尊敬的 微信汇率:1円 ≈ 0.046239 元 支付宝汇率:1円 ≈ 0.04633元 [退出登录]
SlideShare a Scribd company logo
Data Structures using C
Prof. Dr. K ADISESHA
Please bring to class
each day
Introduction
Types of Data structures
Arrays
Stacks and Queues
Linked lists
2
Data Structures
Trees
Introduction
Prof. Dr. K. Adisesha
3
Data Structures:
Data
 Data is a collection of facts, numbers, letters or symbols that the computer process into
meaningful information.
Data structure
 Data structure is representation of the logical relationship existing between individual
elements of data.
 Data structure is a specialized format for organizing and storing data in memory that
considers not only the elements stored but also their relationship to each other.
Introduction
Prof. Dr. K. Adisesha
4
Why to Learn Data Structure:
As applications are getting complex and data rich, there are three common problems
that applications face now-a-days
 Data Search − Consider an inventory of 1 million(106) items of a store. If the
application is to search an item, it has to search an item in 1 million(106) items every
time slowing down the search. As data grows, search will become slower.
 Processor speed − Processor speed although being very high, falls limited if the data
grows to billion records.
 Multiple requests − As thousands of users can search data simultaneously on a web
server, even the fast server fails while searching the data..
Introduction
Prof. Dr. K. Adisesha
5
Data Structures:
Data structures are essential components that help organize and store data efficiently
in computer memory.
 They provide a way to manage and manipulate data effectively, enabling faster access,
insertion, and deletion operations.
Introduction
Prof. Dr. K. Adisesha
6
Data Type:
Data type is a way to classify various types of data which determines the values that can
be used with the corresponding type of data, the type of operations that can be
performed on the corresponding type of data.
There are two data types:
 Built-in Data Type: Those data types for which a language has built-in support are
known as Built-in Data type.
 Derived Data Type: Those data types which are implementation independent as they
can be implemented in one or the other way are known as derived data types.
Data Structures
Prof. Dr. K. Adisesha
7
Classification of Data Structure using C:
Data structure are normally divided into two broad categories:
 Primitive Data Structure
 Non-Primitive Data Structure
 Linear Data Structure
 Non-Linear Data Structure
Data Structures
Prof. K. Adisesha
8
Differences between Data Structure:
The most commonly used differences between on data structure are broadly categorized
into following types:
 A primitive data structure is generally a basic structure that is usually built into the
language, such as an integer, a float.
 A non-primitive data structure is built out of primitive data structures linked together
in meaningful ways, such as a or a linked-list, binary search tree, AVL Tree, graph etc.
Data Structures
Prof. Dr. K. Adisesha
9
Primitive Data Structure:
Data structures that are directly operated upon the machine-level instructions are
known as primitive data structures:
 There are basic structures and directly operated upon by the machine instructions.
 The Data structures that fall in this category are.
 Integer
 Floating-point number
 Character constants
 string constants
 pointers etc.,
Data Structures
Prof. Dr. K. Adisesha
10
Primitive Data Structure:
Data structures that are directly operated upon the machine-level instructions are
known as primitive data structures:
 The most commonly used operation on data structure are broadly categorized into
following types:
 Create
 Insertion
 Selection
 Updating
 Destroy or Delete
Data Structures
Prof. Dr. K. Adisesha
11
Non-Primitive Data Structure:
The Data structures that are derived from the primitive data structures are called Non-
primitive data structure:
 There are more sophisticated data structures
 The non-primitive data structures emphasize on structuring of a group of homogeneous
(same type) or heterogeneous (different type) data items:
 Linear Data structures
 Non-Linear Data structures
Data Structures
Prof. Dr. K. Adisesha
12
Non-Primitive Data Structure:
Linear Data structures
Linear Data structures are kind of data structure that has homogeneous elements.
 The data structure in which elements are in a sequence and form a liner series.
 Linear data structures are very easy to implement, since the memory of the computer is
also organized in a linear fashion.
 Some commonly used linear data structures are:
 Stack
 Queue
 Linked Lists
Data Structures
Prof. Dr. K. Adisesha
13
Non-Primitive Data Structure:
Non-Linear Data structures
A Non-Linear Data structures is a data structure in which data item is connected to
several other data items.
 Non-Linear data structure may exhibit either a hierarchical relationship or parent child
relationship.
 The data elements are not arranged in a sequential structure.
 Some commonly used non-linear data structures are:
 Trees
 Graphs
Data Structures
Prof. Dr. K. Adisesha
14
Non-Primitive Data Structure:
The most commonly used operation on data structure are broadly categorized into
following types:
 Traversal
 Insertion
 Selection
 Searching
 Sorting
 Merging
 Destroy or Delete
Memory Allocation
Prof. Dr. K. Adisesha
15
Memory Allocation in C:
Memory allocation is a process by which computer programs and services are assigned
with physical or virtual memory space.
 The Memory is divided into three sections.
 Heap Memory: It is a part of the main memory. It is unorganized and
treated as a resource when you require the use of it if not release.
 Stack Memory: It stores temporary variables created by a function. In
stack, variables are declared, stored, and initialized during runtime.
 Code Section: Whenever the program is executed it will be brought
into the main memory. This program will get stored under the code
section.
Memory Allocation
Prof. Dr. K. Adisesha
16
Memory Allocation in C:
Memory allocation is a process by which computer programs and services are assigned
with physical or virtual memory space.
 The memory allocation is done either before or at the time of program execution.
 There are two types of memory allocations:
 Compile-time or Static Memory Allocation: Memory is allocated for declared
variables by the compiler.
 Run-time or Dynamic Memory Allocation: Memory allocation done at the time of
execution(run time) is known as dynamic memory allocation.
Memory Allocation
Prof. Dr. K. Adisesha
17
Static Memory Allocation in C:
In static memory allocation the program executes fixes the size that the program is
going to take, and it can’t be changed further. So, the exact memory requirements must
be known before.
 Allocation and deallocation of memory will be done by the compiler automatically.
 Key Features:
 Allocation and deallocation are done by the compiler.
 It uses a data structures stack for static memory allocation.
 Variables get allocated permanently.
 Execution is faster than dynamic memory allocation.
 Memory is allocated before runtime.
Memory Allocation
Prof. Dr. K. Adisesha
18
Dynamic Memory Allocation in C:
In Dynamic memory allocation size initialization and allocation are done by the
programmer. It is managed and served with pointers that point to the newly allocated
memory space in an area which we call the heap.
 Heap memory is unorganized and it is treated as a resource when you require the use of
it if not release it.
 Key Features:
 Dynamic allocated at runtime
 We can also reallocate memory size if needed.
 Dynamic Allocation is done at run time.
 No memory wastage
Memory Allocation
Prof. Dr. K. Adisesha
19
Dynamic Memory Allocation in C:
There are some functions available in the stdlib.h header which will help to allocate
memory dynamically.
 malloc(): function allocates memory at runtime is called malloc() function returns a
pointer with the value NULL. Syntax: int *p = (int*)malloc(No of values*size(int));
 calloc(): function initializes the memory that is allocated so that all bytes are zero.
Syntax: int *p = (int*)calloc(Number of data items, sizeof(int));
 realloc(): The realloc() function enables you to reuse or extend the memory that you
previously allocated using malloc() or calloc().
Syntax: int *np = (type cast) realloc (pointer type, number of elements * sizeof(int));
 free(): When memory is allocated dynamically it should always be released when it is
no longer required. Syntax: free(pointer);
Data Structures
Prof. Dr. K. Adisesha
20
Algorithms and Applications of Data Structures:
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed
in a certain order to get the desired output. Algorithms are generally created
independent of underlying languages.
 From the data structure point of view, following are some important categories of
algorithms.
 Insert − Algorithm to insert item in a data structure.
 Traverse − Algorithm to visit every item in a data structure.
 Update − Algorithm to update an existing item in a data structure.
 Search − Algorithm to search an item in a data structure.
 Sort − Algorithm to sort items in a certain order.
 Delete − Algorithm to delete an existing item from a data structure.
Algorithm
Prof. Dr. K. Adisesha
21
Characteristics of an Algorithm:
An algorithm should have the following characteristics −.
 Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
 Input − An algorithm should have 0 or more well-defined inputs.
 Output − An algorithm should have 1 or more well-defined outputs, and should match
the desired output.
 Finiteness − Algorithms must terminate after a finite number of steps.
 Feasibility − Should be feasible with the available resources.
 Independent − An algorithm should have step-by-step directions, which should be
independent of any programming code.
Algorithm
Prof. Dr. K. Adisesha
22
Characteristics of a Data Structure:
Data Structure is a systematic way to organize data in order to use it efficiently.
Following terms are the Characteristics of a data structure.
 Correctness − Data structure implementation should implement its interface correctly.
 Time Complexity − Running time or the execution time of operations of data structure
must be as small as possible.
 Space Complexity − Memory usage of a data structure operation should be as little as
possible.
Algorithm
Prof. Dr. K. Adisesha
23
Algorithm Analysis:
Efficiency of an algorithm can be analyzed at two different stages, before implementation
and after implementation. They are the following .
 A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an
algorithm is measured by assuming factors, like processor speed, are constant and have
no effect on the implementation.
 A Posterior Analysis − This is an empirical analysis of an algorithm. The selected
algorithm is implemented using programming language. In this analysis, actual statistics
like running time and space required, are collected.
Algorithm
Prof. Dr. K. Adisesha
24
Algorithm Complexity:
The complexity of an algorithm represents the amount of memory space and time
required by the algorithm in its life cycle.
 Space complexity − Space complexity of an algorithm represents the amount of memory
space required by the algorithm in its life cycle..
 Time complexity − Time complexity of an algorithm represents the amount of time
required by the algorithm to run to completion.
Algorithm
 Calculate
 Lines 1 and 4 count for one unit each
 Line 3: executed N times, each time four units
 Line 2: (1 for initialization, N+1 for all the tests, N for all the increments) total 2N + 2
 total cost: 6N + 4  O(N)


N
i
i
1
3 1
2
3
4
1
2N+2
4N
1
Algorithm
Prof. Dr. K. Adisesha
26
Asymptotic Analysis of an algorithm:
Asymptotic analysis of an algorithm refers to Asymptotic analysis refers to computing the
running time of any operation in mathematical units of computation of its run-time
performance.
 The Asymptotic analysis of an algorithm falls under three types:
 Best Case − Minimum time required for program execution.
 Average Case − Average time required for program execution.
 Worst Case − Maximum time required for program execution.
Algorithm
Prof. Dr. K. Adisesha
27
Asymptotic Notations of an algorithm:
Following are the commonly used asymptotic notations to calculate the running time
complexity of an algorithm..
 The Asymptotic Notations of an algorithm falls under three types:
 Big Oh Notation, Ο− It measures the worst case time complexity.
 Omega Notation, Ω− It measures the best case time complexity.
 Theta Notation, θ− It measures the Average case time complexity.
Algorithm
Prof. Dr. K. Adisesha
28
Big Oh Notation, ( Ο )of an algorithm:
The notation Ο(n) is the formal way to express the upper bound of an algorithm's
running time.
 It measures the worst case time complexity or the longest amount of time an algorithm
can possibly take to complete.
 For example, for a function f(n)
 It is represented as follows
 Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0. }
Algorithm
Prof. Dr. K. Adisesha
29
Omega Notation, Ω of an algorithm:
The notation Ω(n) is the formal way to express the lower bound of an algorithm's
running time. It measures the best case time complexity or the best amount of time an
algorithm can possibly take to complete
• For example, for a function f(n)
• It is represented as follows
• Ω(f(n)) ≥ { g(n) : there exists c > 0 and n0 such that g(n) ≤ c.f(n) for all n > n0. }
Algorithm
Prof. Dr. K. Adisesha
30
Theta Notation, θ of an algorithm:
The notation θ(n) is the formal way to express both the lower bound and the upper
bound of an algorithm's running time.
 For example, for a function f(n)
 It is represented as follows
 θ(f(n)) = { g(n) if and only if g(n) = Ο(f(n)) and g(n) = Ω(f(n)) for all n > n0. }
Algorithm
Prof. Dr. K. Adisesha
31
Common Asymptotic Notations:
Following is a list of some common asymptotic notations.
 constant − Ο(1)
 logarithmic− Ο(log n)
 linear − Ο(n)
 n log n − Ο(n log n)
 quadratic − Ο(n2)
 cubic − Ο(n3)
 polynomial − nΟ(1)
 exponential− 2Ο(n)
Recursion
Prof. Dr. K. Adisesha
32
Recursion:
Recursion is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function, then it
is called a recursive call of the function.
 while using recursion, programmers need to be careful to define an exit condition from
the function, otherwise it will go into an infinite loop.
 Recursive functions are very useful to solve many
mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series,
etc.
Recursion
Prof. Dr. K. Adisesha
33
Recursion:
Recursion is the process in which a function calls itself up to n-number of times. If a
program allows the user to call a function inside the same function recursively, the
procedure is called a recursive call of the function.
 Types of Recursion in C:
 Direct Recursion
 Indirect Recursion
 Tail Recursion
 No Tail/ Head Recursion
 Linear recursion
 Tree Recursion
Recursion
Prof. Dr. K. Adisesha
34
Types of the recursion:
Following are the types of the recursion in C programming language, as follows:
 Direct Recursion: When a function calls itself within the same function repeatedly, it
is called the direct recursion.
 Indirect Recursion: When a function is mutually called by another function in a
circular manner, the function is called an indirect recursion function.
Direct Recursion:
fun()
{
// write some code
fun();
// some code
}
Indirect Recursion:
fun1()
{
// write some code
fun2();
}
fun2()
{
// write some code
fun1();
// write some code
}
Recursion
Prof. Dr. K. Adisesha
35
Types of the recursion:
Following are the types of the recursion in C programming language, as follows:
 Tail Recursion: A recursive function is called the tail-recursive if the function makes
recursive calling itself, and that recursive call is the last statement executes by the
function. After that, there is no function or statement is left to call the recursive function.
 Head Recursion: A function is called the non-tail or head recursive if a function makes a
recursive call itself, the recursive call will be the first statement in the function.
 Linear recursion: A function is called the linear recursive if the function makes a single
call to itself at each time the function runs and grows linearly in proportion to the size of
the problem.
 Tree Recursion: A function is called the tree recursion, in which the function makes more
than one call to itself within the recursive function.
Recursion
Prof. Dr. K. Adisesha
36
Recursion:
The C programming language supports recursion, i.e., a function to call itself.
 The following example calculates the factorial of a given number using a recursive
function −
#include <stdio.h>
int factorial(int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %dn", i,
factorial(i));
return 0;
}
Recursion
Prof. Dr. K. Adisesha
37
Drawbacks of Recursion in Data Structure:
There are some potential drawbacks to using recursion in data structures, including:
 Memory usage: Recursive algorithms can use a lot of memory, particularly if the recursion
goes too deep or if the data structure is large. Each recursive call creates a new stack frame on
the call stack, which can quickly add up to a significant amount of memory usage.
 Stack overflow: If the recursion goes too deep, it can cause a stack overflow error, which can
crash the program.
 Performance: Recursive algorithms can be less efficient than iterative algorithms in some
cases, particularly if the data structure is large or if the recursion goes too deep.
 Debugging: Recursive algorithms can be more difficult to debug than iterative algorithms,
particularly if the recursion goes too deep or if the program is using multiple recursive calls.
 Code complexity: Recursive algorithms can be more complex than iterative algorithm.
Recursion
Prof. Dr. K. Adisesha
38
Difference between Recursion and Iteration:
Basis Recursion Iteration
Basis of
repetition
Recursion is based on the idea of a function
calling itself. The base case is the simplest
version of the problem that can be solved
without recursion.
Iteration, on the other hand, uses looping
constructs such as "for" and "while" to repeat
a process a certain number of times or until a
specific condition is met.
Control flow
Recursion relies on the call stack to keep track
of function calls and their parameters. Each
recursive call pushes a new function call onto
the call stack, and each return pops the function
call off the stack.
Iteration, on the other hand, does not rely on
the call stack and uses variables and control
structures to control the flow of execution.
Performance
Recursion can be more elegant and easier to
understand for certain types of problems
Iteration is often more efficient than recursion,
especially for large datasets or complex
algorithms.
Unit -2 Arrays
Prof. Dr. K. Adisesha
39
Arrays:
An array is defined as a set of finite number of homogeneous elements or same data
items:
 Following are the important terms to understand the concept of Array.
 Element − Each item stored in an array is called an element.
 Index − Each location of an element in an array has a numerical index, which is
used to identify the element.
 Declaration of array is as follows:
 Syntax: Datatype Array_Name [Size];
 Example: int arr[10];
 Where int specifies the data type or type of elements arrays stores.
 “arr” is the name of array & the number specified inside the square brackets is the number of
elements an array can store, this is also called sized or length of array.
Arrays
Prof. Dr. K. Adisesha
40
Arrays:
Represent a Linear Array in memory:
 The elements of linear array are stored in consecutive memory locations.
 It is shown below:
int A[5]={23, 4, 6, 15, 5, 7}
Arrays
Prof. Dr. K. Adisesha
41
Calculating the length of the array:
The elements of array will always be stored in the consecutive (continues) memory
location.
 The number of elements that can be stored in an array, that is the size of array or its length is
given by the following equation:
o A[n] is the array size or length of n elements.
o The length of the array can be calculated by:
L = UB – LB + 1
o To Calculate the address of any element in array:
Loc(A[P])=Base(A)+W(P-LB)
o Here, UB is the largest Index and LB is the smallest index
 Example: If an array A has values 10, 20, 30, 40, 50, stored in location 0,1, 2, 3, 4 the UB = 4
and LB=0 Size of the array L = 4 – 0 + 1 = 5
Arrays
Prof. Dr. K. Adisesha
42
Types of Arrays:
The elements of array will always be stored in the consecutive (continues) memory
location. The various types of Arrays are:
 Single Dimension Array:
 Array with one subscript
 Ex: int A[i];
 Two Dimension Array
 Array with two subscripts (Rows and Column)
 Ex: int A[i][j];
 Multi Dimension Array:
 Array with Multiple subscripts
 Ex: int A[i][j]..[n];
Arrays
Prof. Dr. K. Adisesha
43
Abstract Data Type:
ADTs or abstract data types are the ways of classifying data structures by providing a
minimal expected interface and some set of methods.
 Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a
set of values and a set of operations.
 Abstract data types (ADTs) are a way of encapsulating data and operations on that data
into a single unit.
 Array as ADT (Abstract Data Type) mean data structure array and the set of operations:
 Representation of Data.
 Set of Operations on the Data.
Arrays
Prof. Dr. K. Adisesha
44
Basic operations of Arrays:
Some common operation performed on array are:
 Traversing
 Insertion
 Deletion
 Searching
 Sorting
 Merging
Arrays
Prof. Dr. K. Adisesha
45
Traversing Arrays:
Traversing: It is used to access each data item exactly once so that it can be processed:
 We have linear array A as below:
1 2 3 4 5
10 20 30 40 50
 Here we will start from beginning and will go till last element and during this process
we will access value of each element exactly once as below:
A [0] = 10
A [1] = 20
A [2] = 30
A [3] = 40
A [4] = 50
Arrays
Prof. Dr. K. Adisesha
46
Traverse Operation:
Following program traverses and prints the elements of an array:
Arrays
Prof. Dr. K. Adisesha
47
Insertion into Array:
Insertion: It is used to add a new data item in the given collection of data items:
 We have linear array A as below:
1 2 3 4 5
10 20 50 30 15
 New element to be inserted is 100 and location for insertion is 3.
 So shift the elements from 5th location to 3rd location downwards by 1 place.
 And then insert 100 at 3rd location
Arrays
Prof. Dr. K. Adisesha
48
Insertion into Array:
Insertion into Array:
 Insertion 100 into Array
at Pos=3
A [0] = 10
A [1] = 20
A [2] = 50
A [3] = 30
A [4] = 15
Arrays
Prof. Dr. K. Adisesha
49
Insertion into Array: Add a new data item in the given array of data:
Insertion into Array:
A [0] = 1
A [1] = 3
A [2] = 5
A [3] = 7
A [4] = 8
Arrays
Prof. Dr. K. Adisesha
50
Deletion from Array:
Deletion: It is used to delete an existing data item from the given collection of data
items:
 Deletion 30 from Array
at Pos 3
A [0] = 10
A [1] = 20
A [2] = 30
A [3] = 40
A [4] = 50
Arrays
Prof. Dr. K. Adisesha
51
Deletion from Array:
A [0] = 1
A [1] = 3
A [2] = 5
A [3] = 7
A [4] = 8
Arrays Searching
Prof. Dr. K. Adisesha
52
Searching in Arrays:
Searching: It is used to find out the location of the data item if it exists in the given
collection of data items:
 E.g. We have linear array A as below:
1 2 3 4 5
10 20 50 30 35
 Suppose item to be searched is 35. We will start from beginning and will compare 35
with each element.
 This process will continue until element is found or array is finished.
 Types of searching Algorithms:
 Linear searching
 Binary Searching
Arrays Searching
Prof. Dr. K. Adisesha
53
Linear search:
Linear Searching: Also called Sequential Searching.
 It is used to find out the location of the data item if it exists in the given collection of
data items.
 Example Searching element 33 from the array of elements:
Arrays Searching
Prof. Dr. K. Adisesha
54
Linear search:
Linear Searching: Also called Sequential Searching.
Arrays Searching
Prof. Dr. K. Adisesha
55
Binary Searching:
The binary search algorithm can be used with
only sorted list of elements.
 Binary Search first divides a large array into
two smaller sub-arrays and then recursively
operate the sub-arrays.
 Binary Search basically reduces the search
space to half at each step
Arrays Searching
Prof. Dr. K. Adisesha
56
Binary Searching:
The binary search algorithm can be used with only sorted list of elements.
 Example: Searching the element 57 from the array of elements
Arrays Searching
Prof. Dr. K. Adisesha
57
Binary Searching:
 Example:
Arrays Searching
Prof. Dr. K. Adisesha
58
Binary Searching:
Arrays Searching
Prof. Dr. K. Adisesha
59
Difference in Searching:
Arrays Searching
Prof. Dr. K. Adisesha
60
Difference in Searching:
Arrays Sorting
Prof. Dr. K. Adisesha
61
Sorting in Arrays:
A Sorting Algorithm is used to rearrange a given array or list elements according to a
comparison operator on the elements:
 The comparison operator is used to decide the new order of element in the respective
data structure.
 Types of Sorting Algorithms are:
 Bubble Sort
 Insertion Sort
 Selection Sort
 Merge Sort
 Quick Sort
 Heap Sort
 Radix Sort
 Bucket Sort
 Shell Sort
Arrays Sorting
Prof. Dr. K. Adisesha
62
Bubble Sort in Arrays:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.
Arrays Sorting
Prof. Dr. K. Adisesha
63
Bubble Sort in Arrays:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.
Algorithm
begin BubbleSort(arr)
for all array elements
if arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if
end for
return arr
end BubbleSort
Arrays Sorting
Prof. Dr. K. Adisesha
64
Insertion Sorting:
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list)
one item at a time.
 This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained
which is always sorted.
Arrays Sorting
Prof. Dr. K. Adisesha
65
Insertion Sorting:
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained
which is always sorted.
 This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained
which is always sorted.
Arrays Sorting
Prof. Dr. K. Adisesha
66
Insertion Sorting:
 ALGORITHM: Insertion Sort (A, N) A is an array with N unsorted elements.
 Step 1: for I=1 to N-1
 Step 2: J = I
While(J >= 1)
if ( A[J] < A[J-1] ) then
Temp = A[J];
A[J] = A[J-1];
A[J-1] = Temp;
[End if]
J = J-1
[End of While loop]
[End of For loop]
 Step 3: Exit
Arrays Sorting
Prof. Dr. K. Adisesha
67
Selection Sort:
Selection sort is a simple and efficient sorting algorithm that works by repeatedly
selecting the smallest (or largest) element from the unsorted portion of the list and
moving it to the sorted portion of the list.
 To implement the Selection Sort algorithm, we need:
 An array with values to sort.
 An inner loop that goes through the array, finds the lowest value, and moves it to the front
of the array. This loop must loop through one less value each time it runs.
 An outer loop that controls how many times the inner loop must run. For an array with n
 values, this outer loop must run n−1 times.
Arrays Sorting
Prof. Dr. K. Adisesha
68
Selection Sort:
Arrays Sorting
Prof. Dr. K. Adisesha
69
Selection Sort:
Arrays Sorting
Prof. Dr. K. Adisesha
70
Merge Sort Algorithm:
Merge sort is a sorting technique based on divide and conquer technique. Merge sort
first divides the array into equal halves and then combines them in a sorted manner.
 Here’s a step-by-step explanation of how merge sort works:
 Divide: Divide the list or array recursively into two halves
until it can no more be divided.
 Conquer: Each subarray is sorted individually using the merge
sort algorithm.
 Merge: The sorted subarrays are merged back together in
sorted order. The process continues until all elements from both
subarrays have been merged.
Arrays Sorting
Prof. Dr. K. Adisesha
71
Merging from Array:
Merging: It is used to combine the data items of two sorted files into single file in the
sorted form.
 We have sorted linear array A as below:
1 2 3 4 5 6
10 40 50 80 95 100
 And sorted linear array B as below:
1 2 3 4
20 35 45 90
 After merging merged array C is as below:
1 2 3 4 5 6 7 8 9 10
10 20 35 40 45 50 80 90 95 100
Arrays Sorting
Prof. Dr. K. Adisesha
72
Quicksort:
Quicksort is one of the fastest sorting algorithms. This algorithm takes an array of
values, chooses one of the values as the 'pivot' element, and moves the other values so
that lower values are on the left and higher values are on the right of pivot element.
 The algorithm can be described like this:
 Choose a value in the array to be the pivot element.
 Order the rest of the array so that lower values than the pivot element are on the left, and
higher values are on the right.
 Swap the pivot element with the first element of the higher values so that the pivot element
lands in between the lower and higher values.
 Do the same operations (recursively) for the sub-arrays on the left and right side of the pivot
element.
Arrays Sorting
73
Quicksort Algorithms :
Prof. Dr. K. Adisesha
Arrays Sorting
74
Quicksort Algorithms :
Prof. Dr. K. Adisesha
Arrays Sorting
75
Complexity of Sorting Algorithms :
Prof. Dr. K. Adisesha
Arrays
Prof. Dr. K. Adisesha
76
Two dimensional array:
A two dimensional array is a collection of elements and each element is identified by a
pair of subscripts. ( A[3] [3] ).
 The elements are stored in continuous memory locations.
 The elements of two-dimensional array as rows and columns.
 The number of rows and columns in a matrix is called as the order of the matrix and
denoted as MxN.
 The number of elements can be obtained by multiplying number of rows and number of
columns. A[0] A[1] A[2]
A[0] 10 20 30
A[1] 40 50 60
A[2] 70 80 90
Arrays
Prof. Dr. K. Adisesha
77
Representation of Two Dimensional Array:
A two dimensional array is a collection of elements and each element is identified by a
pair of subscripts. ( A[m] [n] )
 A is the array of order m x n. To store m*n number of elements, we need m*n memory
locations.
 The elements should be in contiguous memory locations.
 There are two methods:
 Row-major method
 Column-major method
A[0] A[1] A[2]
A[0] 10 20 30
A[1] 40 50 60
A[2] 70 80 90
Arrays
Prof. Dr. K. Adisesha
78
Representation of Two Dimensional Array:
Row-Major Method:
 All the first-row elements are stored in sequential
memory locations and then all the second-row
elements are stored and so on. Ex: A[Row][Col]
Column-Major Method:
 All the first column elements are stored in sequential
memory locations and then all the second-column
elements are stored and so on. Ex: A [Col][Row]
1000 10 A[0][0]
1002 20 A[0][1]
1004 30 A[0][2]
1006 40 A[1][0]
1008 50 A[1][1]
1010 60 A[1][2]
1012 70 A[2][0]
1014 80 A[2][1]
1016 90 A[2][2]
1000 10 A[0][0]
1002 40 A[1][0]
1004 70 A[2][0]
1006 20 A[0][1]
1008 50 A[1][1]
1010 80 A[2][1]
1012 30 A[0][2]
1014 60 A[1][2]
1016 90 A[2][2]
Row-Major Method
Col-Major Method
Arrays
Prof. Dr. K. Adisesha
79
Calculating the length of the 2D-Array
:
A two dimensional array is a collection of elements and each element is identified by a
pair of subscripts. ( A[m] [n] )
 The size of array or its length is given by the following equation:
A[i][j] is the array size or length of m*n elements.
 To Calculate the address of i*j th element in array:
 Row-Major Method: Loc(A[i][j])=Base(A)+W[n(i-LB)+(j-LB)]
 Col-Major Method: Loc(A[i][j])=Base(A)+W[(i-LB)+m(j-LB)]
Here, W is the number of words per memory location and LB is the smallest index
Arrays
Prof. Dr. K. Adisesha
80
Sparse matrix:
Sparse matrices are those matrices that have the majority of their elements equal to zero.
 In other words, the sparse matrix can be defined as the matrix that has a greater number
of zero elements than the non-zero elements.
 Representing a sparse matrix by a 2D array leads to the wastage of lots of memory. In
2D array representation of sparse matrix, there are three fields used that are named as -
Arrays
Prof. Dr. K. Adisesha
81
Advantages of Array
:
A two dimensional array is a collection of elements and each element is identified by a
pair of subscripts. ( A[m] [n] )
 It is used to represent multiple data items of same type by using single name.
 It can be used to implement other data structures like linked lists, stacks, queues, tree,
graphs etc.
 Two-dimensional arrays are used to represent matrices.
 Many databases include one-dimensional arrays whose elements are records.
Arrays
Prof. Dr. K. Adisesha
82
Disadvantages of Array:
A two dimensional array is a collection of elements and each element is identified by a
pair of subscripts. ( A[m] [n] )
 We must know in advance the how many elements are to be stored in array.
 Array is static structure. It means that array is of fixed size. The memory which is
allocated to array cannot be increased or decreased.
 Array is fixed size; if we allocate more memory than requirement then the memory
space will be wasted.
 The elements of array are stored in consecutive memory locations. So insertion and
deletion are very difficult and time consuming.
Unit 3 Linked List
Prof. Dr. K. Adisesha
83
Lists (linked list):
A lists (Linear linked list) can be defined as a collection of variable number of
data items called nodes.
 Lists are the most commonly used non-primitive data structures.
 Each nodes is divided into two parts:
 The first part contains the information of the element.
 The second part contains the memory address of the next node in the list.
Also called Link part.
Linked List
Prof. Dr. K. Adisesha
84
Lists (linked list):
Types of linked lists:
 Single linked list
 Doubly linked list
 Single circular linked list
 Doubly circular linked list
Linked List
Prof. Dr. K. Adisesha
85
Single linked list:
The link field of the last node contains the memory address of the first node,
such a linked list is called circular linked list:
 The information field contains the data of that node.
 The link field contains the memory address of the next node.
 The last link field contains the memory address as null ().
 There is only one link field in each node, the linked list is called singly linked
list.
Linked List
Prof. Dr. K. Adisesha
86
Single circular linked list:
A singly linked list contains two fields in each node - an information field and
the linked field:
 The information field contains the data of that node.
 The link field contains the memory address of the next node
 The last link field contains the memory address of the first node.
 In a circular linked list every node is accessible from a given node.
Linked List
Prof. Dr. K. Adisesha
87
Doubly linked list:
It is a linked list in which each node is points both to the next node and also
to the previous node:
 In doubly linked list each node contains three parts:
 FORW : It is a pointer field that contains the address of the next node
 BACK: It is a pointer field that contains the address of the previous node.
 INFO: It contains the actual data.
 In the first node, if BACK contains NULL, it indicated that it is the first node in
the list.
 The in which FORW contains, NULL indicates that the node is the last node.
Linked List
Prof. Dr. K. Adisesha
88
Doubly circular linked list:
It is a linked list in which each node is points both to the next node and also to
the previous node:
 In doubly linked list each node contains three parts:
 FORW : It is a pointer field that contains the address of the next node
 BACK: It is a pointer field that contains the address of the previous node.
 INFO: It contains the actual data.
Linked List
Prof. Dr. K. Adisesha
89
Operation on Linked List:
The operation that are performed on linked lists are:
 Creating a linked list
 Traversing a linked list
 Inserting an item into a linked list.
 Deleting an item from the linked list.
 Searching an item in the linked list
 Merging two or more linked lists.
Linked List
Prof. Dr. K. Adisesha
90
Creating a linked list:
The nodes of a linked list can be created by the following structure declaration:
struct Node
{
int information;
struct Node *link;
}*node1, *node2;
 Here info is the information field and link is the link field.
 The link field contains a pointer variable that refers the same node structure. Such a
reference is called as Self addressing pointer.
Linked List
Prof. Dr. K. Adisesha
91
Creating a linked list:
The nodes of a linked list can be created by the following structure declaration:
Linked List
Prof. Dr. K. Adisesha
92
Operator new and delete:
The nodes of a linked list can be created by the following structure declaration:
 Operators new allocate memory space
 Operators new [ ] allocates memory space for array.
 Operators delete deallocate memory space.
 Operators delete [ ] deallocate memory space for array.
struct Node
{
int information;
struct Node *link;
}*node1, *node2;
93
Traversing is the process of accessing each node of the linked list exactly once to
perform some operation.
ALGORITHM: TRAVERS (START, P)
START contains the address of the first node. Another pointer p is temporarily used to visit all the nodes
from the beginning to the end of the linked list.
Step 1: P = START
Step 2: while P != NULL
Step 3: PROCESS data (P) [Fetch the data]
Step 4: P = link(P) [Advance P to next node]
Step 5: End of while
Step 6: Return
Traversing a linked list
Prof. Dr. K. Adisesha
Code:
struct node *temp = head;
printf("nnList elements are - n");
while(temp != NULL) {
printf("%d --->",temp->data);
temp = temp->next;
}
94
 Inserting a node at the beginning of the linked list
 Inserting a node at the given position.
 Inserting a node at the end of the linked list.
Linked List
Inserting a node into the linked list:
Prof. Dr. K. Adisesha
95
Linked List
Inserting node at Front:
Inserting a node at the beginning of the linked list
1. Create a node.
2. Fill data into the data field of the new node.
3. Mark its pointer field as NULL
4. Attach this newly created node to START
5. Make the new node as the START node.
Prof. Dr. K. Adisesha
96
Linked List
Inserting node at Front:
Inserting a node at the beginning of the linked list
ALGORITHM: INS_BEG (START, P) START contains the address of the first node.
Step 1: P new Node;
Step 2: data(P) num;
Step 3: link(P) START
Step 4: START P
Step 5: Return
Prof. Dr. K. Adisesha
97
Linked List
Inserting node at Front:
Inserting a node at the beginning of the linked list
 Get the new node using getnode().
newnode = getnode();
 If the list is empty then start = newnode.
 If the list is not empty, follow the steps given below:
newnode -> next = start;
start = newnode;
Prof. Dr. K. Adisesha
void insert_at_beg()
{ node *newnode;
newnode = getnode();
if(start == NULL)
{ start = newnode; }
else
{ newnode -> next = start;
start = newnode;}
}
98
Linked List
Inserting node at End:
Inserting a node at the End of the linked list
1. Create a node.
2. Fill data into the data field of the new node.
3. Mark its pointer field as NULL
4. Attach this newly created node to Last
5. Make the new node as the Last node.
Prof. Dr. K. Adisesha
ALGORITHM: INS_END (START, P)
START contains the address of the first node.
Step 1: START
Step 2: P START [identify the last node]
while P!= null
P next (P)
End while
Step 3: N new Node;
Step 4: data(N) item;
Step 5: link(N) null
Step 6: link(P) N
Step 7: Return
99
Inserting node at End
Prof. Dr. K. Adisesha
Insert at the End
100
Inserting node at End
Prof. Dr. K. Adisesha
 Allocate memory for new node
 Store data
 Traverse to last node
 Change next of last node to recently created node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = NULL;
struct node *temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
101
Inserting node at a given Position
Inserting a node at intermediate position:
Figure shows inserting a node into the single linked list at a specified intermediate
position other than beginning and end.
Prof. Dr. K. Adisesha
102
Inserting node at a given Position
ALGORITHM: INS_POS (START, P1, P2)
START contains the address of the first node. P2 is new node
Step 1: START
Step 2: P1 START [Initialize node]
Count 0
Step 3: while P!= null
count count+1
P1 next (P1)
End while
Step 4: if (POS=1)
Call function INS_BEG( )
else if (POS=Count +1)
Call function INS_END( )
else if (POS<=Count)
P1 Start
For(i=1; i<=pos; i++)
P1 next(P1);
end for
[create] P2 new node
data(P2) item;
link(P2) link(P1)
link(P1) P2
else
PRINT “Invalid position”
Step 5: Return
Prof. Dr. K. Adisesha
103
Inserting node at a given Position
Code: Insert at the Middle
Prof. Dr. K. Adisesha
 Allocate memory and store data for new node
 Traverse to node just before the required position of new node
 Change next pointers to include new node in between
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
struct node *temp = head;
for(int i=2; i < position; i++) {
if(temp->next != NULL) {
temp = temp->next;
}
}
newNode->next = temp->next;
temp->next = newNode;
104
Deleting an item from the linked list:
 Deletion of the first node
 Deletion of the last node
 Deletion of the node at the give position.
Deleting an node
Deleting an node:
Prof. Dr. K. Adisesha
105
Deleting an node
Deletion of the first node:
This algorithm first copies data in the first node to a variable and delete the first node
of the linked list.
ALGORITHM: DEL_BEG(P, START) This used pointers P
Step 1: START
Step 2: P START;
Step 3: PRINT data(P)
Step 4: START Link(P)
Step 5: Free(P)
Step 6: STOP
Prof. Dr. K. Adisesha
Start = start->link;
106
Deleting an node
Deletion of the first node:
The following steps are followed, to delete a node at the beginning of the list:
void delete_at_beg()
{ node *temp;
if(start == NULL)
{ printf("n No nodes are exist..");
return ; }
else
{ temp = start;
start = temp -> next;
free(temp);
printf("n Node deleted "); }
}
Prof. Dr. K. Adisesha
 If the list is empty, Display the empty list message
 If the list is not empty, follow the steps given below:
temp = start;
start = start -> next;
free(temp);
107
Deleting an node
Deleting node from end:
Prof. Dr. K. Adisesha
The following steps are followed to delete a node at the end of the list:
 If the list is not empty, follow the steps given below:
temp = prev = start;
while(temp -> next != NULL)
{
prev = temp;
temp = temp -> next;
}
prev -> next = NULL;
free(temp);
ALGORITHM: DEL_END (P1, P2, START) This used two pointers P1 and P2. Pointer P2 is used
to traverse the linked list and pointer P1 keeps the location of the previous node of P2.
Step 1: START
Step 2: P2 START;
Step 3: while ( link(P2) ! = NULL)
P1 P2
P2 link(P2)
While end
Step 4: PRINT data(p2)
Step 5: link(P1) NULL
Free(P2)
Step 6: STOP
108
Deleting an node
Deleting node from end:
Prof. Dr. K. Adisesha
 Traverse to second last element
 Change its next pointer to null
Code:
struct node * temp = head;
while(temp->next->next!=NULL){
temp = temp->next;
}
temp->next = NULL;
109
Deleting an node
Deleting node from end:
Prof. Dr. K. Adisesha
Step 1: START
Step 2: P1 START [Initialize node]
Count 0
Step 3: while P!= null
count count+1
P1 next (P1)
End while
Step 4: if (POS=1)
Call function DEL_BEG( )
else if (POS=Count)
Call function DEL_END( )
else if (POS<=Count)
P2 Start
For(i=1; i<=pos; i++)
P1 P2
P2 link(P2)
end for
PRINT data(P2)
link(P1) link( P2)
free(P2)
End if
Step 5: Return
110
Deleting node at a given Position
ALGORITHM: DEL_POS (START, P1, P2)
START contains the address of the first node. P2 is DEL-node
Prof. Dr. K. Adisesha
111
Deleting node at a given Position
Delete from middle
Prof. Dr. K. Adisesha
 Traverse to element before the element to be deleted
 Change next pointers to exclude the node from the chain
Code:
struct node* temp = head;
for(int i=2; i< position; i++) {
if(temp->next!=NULL) {
temp = temp->next;
}
}
temp->next = temp->next->next;
Unit 4- Stack & Queues
Prof. Dr. K. Adisesha
112
Stack:
Stack is a linear data structure which follows a particular order in which the operations
are performed
 Insertion of element into stack is called PUSH and deletion of element from stack is
called POP.
 The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Stack
Prof. Dr. K. Adisesha
113
Stack:
Memory Representation of Stack
 The stack can be implemented into two ways:
 Using arrays (Static implementation)
 Using pointer (Dynamic
Stack
Prof. Dr. K. Adisesha
114
Operation on Stacks:
The various operation performed on Stacks are:
 Stack( ): It creates a new stack that is empty. It needs no parameter and returns an
empty stack.
 push(item): It adds a new item to the top of the stack.
 pop( ): It removes the top item from the stack.
 peek( ): It returns the top item from the stack but does not remove it.
 isEmpty( ): It tests whether the stack is empty.
 size( ): It returns the number of items on the stack.
Stack
Prof. Dr. K. Adisesha
115
Stack Conditions:
The various operation performed on Stacks depend on the following conditions:
Stack
Prof. Dr. K. Adisesha
116
PUSH Operation:
The process of adding one element or item to the stack is represented by an operation
called as the PUSH operation:
ALGORITHM:
PUSH (STACK, TOP, SIZE, ITEM)
STACK is the array with N elements. TOP is the pointer to the top of the element of the array. ITEM to be inserted.
Step 1: if TOP = N then [Check Overflow]
PRINT “ STACK is Full or Overflow”
Exit
[End if]
Step 2: TOP = TOP + 1 [Increment the TOP]
Step 3: STACK[TOP] = ITEM [Insert the ITEM]
Step 4: Return
Stack
Prof. Dr. K. Adisesha
117
POP Operation:
The process of deleting one element or item from the stack is represented by an
operation called as the POP operation.
When elements are removed continuously from a stack, it shrinks at same end i.e., top:
ALGORITHM: POP (STACK, TOP, ITEM)
STACK is the array with N elements. TOP is the pointer to the top of the element of the array. ITEM
to be DELETED.
Step 1: if TOP = 0 then [Check Underflow]
PRINT “ STACK is Empty or Underflow”
Exit
[End if]
Step 2: ITEM = STACK[TOP] [copy the TOP Element]
Step 3: TOP = TOP - 1 [Decrement the TOP]
Step 4: Return
Stack
Prof. Dr. K. Adisesha
118
POP Operation:
The process of deleting one element or item from the stack is represented by an
operation called as the POP operation.
Stack
Prof. Dr. K. Adisesha
119
PEEK Operation:
The process of returning the top item from the stack but does not remove it called as the
PEEK operation.
ALGORITHM: PEEK (STACK, TOP)
STACK is the array with N elements. TOP is the pointer to the top of the element of the
array.
Step 1: if TOP = NULL then [Check Underflow]
PRINT “ STACK is Empty or Underflow”
Exit
[End if]
Step 2: Return (STACK[TOP] [Return the top element of the stack]
Step 3:Exit
Stack
Prof. Dr. K. Adisesha
120
Program to demonstrate push and pop operation in stack in data structure in C
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
int top = -1, A[SIZE];
void push();
void pop();
void show();
int main()
{ int choice;
while (1)
{ printf("nPerform operations on the stack:");
printf("n1.Push n 2.Pop n 3.Shown4.End");
printf("nnEnter the choice: ");
scanf("%d", &choice);
switch (choice)
{ case 1:
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
case 4:
exit(0);
default:
printf("nInvalid choice!!");
} }
}
Stack
Prof. Dr. K. Adisesha
121
Program to demonstrate push and pop operation in stack in data structure in C
void push()
{ int x;
if (top == SIZE - 1)
{ printf("nOverflow!!"); }
else
{ printf("nEnter the element to the stack: ");
scanf("%d", &x);
top = top + 1;
A[top] = x; }
}
void pop()
{ if (top == -1)
{ printf("nUnderflow!!"); }
else
{ printf("nPopped element: %d", A[top]);
top = top - 1; }
}
void show()
{ if (top == -1)
{ printf("nUnderflow!!"); }
else
{ printf("nElements present in the stack: n");
for (int i = top; i >= 0; --i)
printf("%dn", A[i]);
}
}
Stack
Prof. Dr. K. Adisesha
122
Application of Stacks:
 It is used to reverse a word. You push a given word to stack – letter by letter and then pop
letter from the stack.
 “Undo” mechanism in text editor.
 Conversion of infix expression into prefix and postfix.
 Evaluation of Arithmetic Expressions
 Delimiter Checking
 Processing Function Calls
 To solve tower of Hanoi.
 To sort elements using Quick sort
 Runtime memory management.
An expression is a combination of operands and operators that after evaluation results
in a single value.
 Operand consists of constants and variables.
 Operators consists of {, +, -, *, /, ), ] etc.
 Expression can be
 Infix Expression: If an operator is in between two operands, it is called infix expression.
 Example: a + b, where a and b are operands and + is an operator.
 Postfix Expression: If an operator follows the two operands, it is called postfix expression.
 Example: ab +
 Prefix Expression: an operator precedes the two operands, it is called prefix expression.
 Example: +ab
Stack
Prof. Dr. K. Adisesha
123
Arithmetic Expression:
Stack
Prof. Dr. K. Adisesha
124
Arithmetic Expression:
Converting an infix expression into a
postfix expression.
A+B/C+D*(E-F)^G
Stack
Prof. Dr. K. Adisesha
125
Arithmetic Expression:
Stack
Prof. Dr. K. Adisesha
126
Arithmetic Expression:
Evaluating Postfix expression:
 let us consider the following infix expression:
2 * (4+3) - 5.
 Its equivalent postfix expression is:
2 4 3 + * 5.
 The following step illustrates how this postfix
expression is evaluated.
Value=9
Stack
Prof. Dr. K. Adisesha
127
Delimiter Checking:
The common application of Stack is delimiter checking, i.e., parsing that involves
analyzing a source program syntactically.
 To perform a delimiter checking, the compiler makes use of a stack.
 It is also called parenthesis checking.
Valid Delimiter Invalid Delimiter
While ( i > 0) While ( i >
/* Data Structure */ /* Data Structure
{ ( a + b) - c } { ( a + b) - c
Stack
Prof. Dr. K. Adisesha
128
Processing Function Calls:
A call stack is a data structure used by computer programs to keep track of function calls.
 When a Recursive function is called, a new frame is added to the call stack.
function factorial(n)
{ if (n == 0)
{
return 1;
}
else
{ return n * factorial(n - 1);
}
}
Queue
Prof. Dr. K. Adisesha
129
Queue:
A queue is an ordered collection of items where an item is inserted at one end called the
“rear” and an existing item is removed at the other end, called the “front”.
 Queue is also called as FIFO list i.e. First-In First-Out.
 In the queue only two operations are allowed enqueue and dequeue.
 Enqueue means to insert an item into back of the queue.
 Dequeue means removing the front item.The people standing in a railway reservation
row are an example of queue.
Queue
Prof. Dr. K. Adisesha
130
Queue:
A queue is an ordered collection of items where an item is inserted at one end called the
“rear” and an existing item is removed at the other end, called the “front”.
Queue
Prof. Dr. K. Adisesha
131
Memory Representation of Queue:
The queue can be implemented into two ways:
 Using arrays (Static implementation)
 Using pointer (Dynamic
Queue
Prof. Dr. K. Adisesha
132
Memory Representation of Queue:
Memory Representation of a queue using array:
 Queue is represented in memory using linear array.
 Let QUEUE is a array, two pointer variables called FRONT and REAR are
maintained.
 The pointer variable FRONT contains the location of the element to be removed or
deleted.
 The pointer variable REAR contains location of the last element inserted.
 The condition FRONT = NULL indicates that queue is empty.
 The condition REAR = N-1 indicates that queue is full.
Queue
Prof. Dr. K. Adisesha
133
Types of Queues
:
Queue can be of four types:
 Simple Queue
 Circular Queue
 Priority Queue
 De-queue ( Double Ended Queue)
Queue
Prof. Dr. K. Adisesha
134
Types of Queues
:
Simple Queue: Simple Queue is a linear data structure that follows the First-In-First-
Out (FIFO) principle, where elements are added to the rear (back) and removed from
the front (head).
 When a new element is added, all elements added before the new element must be
deleted in order to remove the new element.
 Ordered collection of comparable data kinds.
 Queue structure is FIFO (First in, First Out).
Queue
Prof. Dr. K. Adisesha
135
Types of Queues
:
Circular Queue:
A circular queue is a special case of a simple queue in which the last member is linked
to the first, forming a circle-like structure.
 The last node is connected to the first node.
 Also known as a Ring Buffer, the nodes are connected
end to end.
 Insertion takes place at the front of the queue, and
deletion at the end of the queue.
Queue
Prof. Dr. K. Adisesha
136
Types of Queues
:
Priority Queue:
In a priority queue, the nodes will have some predefined priority in the priority queue.
The node with the higiest priority will be the first to be removed from the queue. Insertion
takes place in the order of arrival of the nodes.
 Some of the applications of priority queue:
 Dijkstra’s shortest path algorithm
 Prim’s algorithm
 Data compression techniques like Huffman
code
Queue
Prof. Dr. K. Adisesha
137
Types of Queues
:
Dequeue Queue:
 Dequeue: It is a queue in which insertion and deletion takes place at the both ends.
Queue
Prof. Dr. K. Adisesha
138
Operation on Queues
:
The various operation performed on Queue are :
Operation Description
enqueue() Process of adding or storing an element to the end of the queue
dequeue() Process of removing or accessing an element from the front of the queue
peek() Used to get the element at the front of the queue without removing it
initialize() Creates an empty queue
isfull() Checks if the queue is full
isempty() Check if the queue is empty
Queue
Prof. Dr. K. Adisesha
139
Queue Insertion Operation (ENQUEUE):
ALGORITHM: ENQUEUE (QUEUE, REAR, FRONT, ITEM)
QUEUE is the array with N elements. FRONT is the pointer that contains the location of the element to be deleted
and REAR contains the location of the inserted element. ITEM is the element to be inserted.
Step 1: if REAR = N-1 then [Check Overflow] Front Rear
PRINT “QUEUE is Full or Overflow”
Exit
[End if]
Step 2: if FRONT = NULL then [Check Whether Queue is empty]
FRONT = -1
REAR = -1
else
REAR = REAR + 1 [Increment REAR Pointer]
Step 3: QUEUE[REAR] = ITEM [Copy ITEM to REAR position]
Step 4: Return
Queue
Prof. Dr. K. Adisesha
140
Queue Deletion Operation (DEQUEUE):
 ALGORITHM: DEQUEUE (QUEUE, REAR, FRONT, ITEM)
QUEUE is the array with N elements. FRONT is the pointer that contains the location of the element to be deleted and REAR
contains the location of the inserted element. ITEM is the element to be inserted.
 Step 1: if FRONT = NULL then [Check Whether Queue is empty] Front Rear
 PRINT “QUEUE is Empty or Underflow”
 Exit
 [End if]
 Step 2: ITEM = QUEUE[FRONT]
 Step 3: if FRONT = REAR then [if QUEUE has only one element]
 FRONT = NULL
 REAR = NULL
 else
 FRONT = FRONT + 1 [Increment FRONT pointer]
 Step 4: Return
Queue
Prof. Dr. K. Adisesha
141
Application of Queue:
 Operating systems: Operating systems often use queues to manage processes and resources.
For example, a process scheduler might use a queue to manage the order in which processes
are executed.
 Task Scheduling: Queues can be used to schedule tasks based on priority or the order in
which they were received.
 Resource Allocation: Queues can be used to manage and allocate resources, such as
printers or CPU processing time.
 Event Handling: Queues can be used to handle events in event-driven systems, such as GUI
applications or simulation systems.
 Printer queues: In printing systems, queues are used to manage the order in which print jobs
are processed. Jobs are added to the queue as they are submitted, and the printer processes
them in the order they were received.
Unit- 5
Prof. Dr. K. Adisesha
142
Non-Linear Data structures:
Non-linear data structures in C the data is stored in multiple levels. The
implementation of non-linear data structures is more complex than linear data
structures
 The different non-linear data structures are
 Trees
 Graphs.
Non-Linear Data structures
Prof. Dr. K. Adisesha
143
Non-Linear Data structures:
A Non-Linear Data structures is a data structure in which data item is
connected to several other data items:
 The data items in non-linear data structure represent hierarchical relationship.
 Each data item is called node.
 The different non-linear data structures are
 Trees
 Graphs.
Non-Linear Data structures
Prof. Dr. K. Adisesha
144
Tree as data structure :
A tree is a data structure consisting of nodes organized as a hierarchy:
 Tree is a hierarchical data structure which stores the information naturally in the form
of hierarchy style.
 It is a non-linear data structure compared to arrays, linked lists, stack and queue.
 It represents the nodes connected by edges.
Non-Linear Data structures
Prof. Dr. K. Adisesha
145
Terminology of a Tree:
Non-Linear Data structures
Prof. Dr. K. Adisesha
146
Tree as Data structure :
Different Types of Trees in Data Structure:
 Binary Tree
 Ternary Tree
 N-ary Tree
 AVL Tree
 Red-Black Tree
 Binary Search-Tree
 B- Tree
Non-Linear Data structures
Prof. Dr. K. Adisesha
147
Different Types of Trees in Data Structure:
 Binary Tree : A Binary Tree is composed of nodes, where each node has at most two children,
referred to as the left and right subtrees.
 Ternary Tree : A Ternary Tree is a tree data structure in which each node has at most three
child nodes, usually distinguished as “left”, “mid” and “right”.
 N-ary Tree: An N-ary Tree is a generalisation of binary trees where each node can have up to
N children, providing a more flexible and scalable hierarchical structure.
 AVL Tree: AVL tree is a self-balancing Binary Search Tree (BST) where the difference
between heights of left and right subtrees for any node cannot be more than one.
 Red-Black Tree: A Red-Black Tree is a self-balancing binary search tree with the key
innovation of assigning colours (red or black) to its nodes.
Non-Linear Data structures
Prof. Dr. K. Adisesha
148
Binary Tree:
A binary tree is an ordered tree in which each internal node can have maximum
of two child nodes connected to it:
 A binary tree consists of:
 A node ( called the root node)
 Left and right sub trees.
 A Complete binary tree is a binary tree in which each leaf is at the same distance from
the root i.e. all the nodes have maximum two subtrees.
Binary tree using array represents a node which is
numbered sequentially level by level from left to
right. Even empty nodes are numbered.
Non-Linear Data structures
Prof. Dr. K. Adisesha
149
Binary Search tree:
In a Binary search tree, the value of left node must be smaller than the parent
node, and the value of right node must be greater than the parent node.
 A binary search tree follows some order to arrange the elements.
 we can observe that the root node is 40, and all the nodes of the left subtree are smaller
than the root node, and all the nodes of the right subtree are greater than the root node.
 Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50
 Steps - Insert 45 as Root.
Non-Linear Data structures
Prof. Dr. K. Adisesha
150
Full Binary Tree vs. Complete Binary Tree:
A full binary tree can be defined as a binary tree in which all the nodes have 0 or
two children.
 In other words, the full binary tree can be defined as a binary tree in which all the
nodes have two children except the leaf nodes.
 A binary tree is said to be a complete binary tree when all the levels are completely
filled except the last level, which is filled from the left.
Full Binary Tree
Complete Binary Tree
Non-Linear Data structures
Prof. Dr. K. Adisesha
151
Tree traversal:
The term 'tree traversal' means traversing or visiting each node of a tree.
 A Tree Data Structure can be traversed in following ways:
 Depth First Search or DFS
 Inorder Traversal
 Preorder Traversal
 Postorder Traversal
 Breadth First Search or BFS
 Boundary Traversal
 Diagonal Traversal
Non-Linear Data structures
Prof. Dr. K. Adisesha
152
Depth First Search or DFS
DFS, Depth First Search, is an edge-based technique.
 It uses the Stack data structure and performs two stages, first visited vertices are
pushed into the stack, and second if there are no vertices then visited vertices are
popped.
 Depth First Search or DFS
 Inorder Traversal
 Preorder Traversal
 Postorder Traversal
Non-Linear Data structures
Prof. Dr. K. Adisesha
153
Depth First Search or DFS
Inorder Traversal: This technique follows the 'left root right' policy.
It means that first left subtree is visited after that root node is traversed, and finally, the
right subtree is traversed.
Algorithm: Until all nodes of the tree are not visited
Step 1 - Traverse the left subtree recursively.
Step 2 - Visit the root node.
Step 3 - Traverse the right subtree recursively.
Non-Linear Data structures
Prof. Dr. K. Adisesha
154
Depth First Search or DFS
Preorder Traversal: This technique follows the 'root left right' policy.
It means that, first root node is visited after that the left subtree is traversed recursively,
and finally, right subtree is recursively traversed.
Algorithm: Until all nodes of the tree are not visited
Step 1 - Visit the root node
Step 2 - Traverse the left subtree recursively.
Step 3 - Traverse the right subtree recursively.
Non-Linear Data structures
Prof. Dr. K. Adisesha
155
Depth First Search or DFS
:
Postorder Traversal: This technique follows the 'left-right root' policy.
It means that the first left subtree of the root node is traversed, after that recursively
traverses the right subtree, and finally, the root node is traversed.
Algorithm: Until all nodes of the tree are not visited
Step 1 - Traverse the left subtree recursively.
Step 2 - Traverse the right subtree recursively.
Step 3 - Visit the root node.
Non-Linear Data structures
Prof. Dr. K. Adisesha
156
Depth First Search or DFS
:
Construct Tree from given Inorder and Preorder traversals.
Let us consider the below traversals:
 Inorder sequence: D B E A F C
 Preorder sequence: A B D E C F
In a Preorder sequence, the leftmost element is the root of the
tree. So we know ‘A’ is the root for given sequences.
By searching ‘A’ in the Inorder sequence, we can find out all
elements on the left side of ‘A’ is in the left subtree and
elements on right in the right subtree.
So we know the below structure now.
Non-Linear Data structures
Prof. Dr. K. Adisesha
157
Depth First Search or DFS:
Construct Tree from given Inorder and Preorder traversals.
Algorithm: buildTree()
 Pick an element from Preorder. Increment a Preorder Index Variable to pick the next element
in the next recursive call.
 Create a new tree node tNode with the data as the picked element.
 Find the picked element’s index in Inorder. Let the index be inIndex.
 Call buildTree for elements before inIndex and make the built tree as a left subtree of tNode.
 Call buildTree for elements after inIndex and make the built tree as a right subtree of tNode.
 return tNode.
Non-Linear Data structures
Prof. Dr. K. Adisesha
158
Breadth First Search or BFS
:
BFS, Breadth-First Search, is a vertex-based technique for finding the shortest
path in the graph.
 It uses a Queue data structure that follows first in first out.
 Breadth First Search or BFS
 Boundary Traversal
 Diagonal Traversal
Non-Linear Data structures
Prof. Dr. K. Adisesha
159
Applications of tree data structure
Trees find applications in various fields, including.
 Storing hierarchical data in File System
 In chess game to store defense moves of player.
 In server like DNS (Domain Name Server)
 Web Search Engines
 Computer Graphics.
 To evaluate an expression
 GPS Navigation systems
 Artificial Intelligence
Non-Linear Data structures
Prof. Dr. K. Adisesha
160
Graph:
Graph is a mathematical non-linear data structure capable of representing many
kind of physical structures:
 A graph is a set of vertices and edges which connect them.
 A graph is a collection of nodes called vertices and the connection between them
called edges.
 Definition: A graph G(V,E) is a set of vertices V and a set of edges E.
Non-Linear Data structures
Prof. Dr. K. Adisesha
161
Graph:
Graph is a mathematical non-linear data structure capable of representing many
kind of physical structures:
 An edge connects a pair of vertices and many have weight such as length, cost and
another measuring instrument for according the graph.
 Vertices on the graph are shown as point or circles and edges are drawn as arcs or line
segment
Non-Linear Data structures
Prof. Dr. K. Adisesha
162
Graph:
Types of Graphs:
 Directed graph
 Undirected graph
 Simple graph
 Weighted graph
 Connected graph
 Non-connected graph
Non-Linear Data structures
Prof. Dr. K. Adisesha
163
Graph Representation:
There are two techniques to represent a graph:
 Adjacency Matrix: In the adjacency matrix, each row and column define a vertex. It is
a 2D array of V x V vertices.
 Adjacency List: The index of the array defines a vertex, and every component in its
linked list describes the other vertices that form an edge with the vertex.
Adjacency Matrix Adjacency List
Non-Linear Data structures
Prof. Dr. K. Adisesha
164
Applications of Graph Data Structure:
In Computer science graphs are used to represent the flow of computation.
 Graphs are used to represent networks of communication.
 Graph theory is also used in network security.
 In Google Maps, is used to find shortest path in road or a network.
 The World Wide Web is an example of a directed graph.
 Facebook uses undirected graphs to identify a user and the user’s friends.
 In Electrical Engineering, graph theory is used in designing of circuit connections.
 graph data structures define and compute the transport system.
Data structures
Prof. Dr. K. Adisesha
165
Thank you:

More Related Content

Similar to Data Structure using C by Dr. K Adisesha .ppsx

DS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxDS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptx
prakashvs7
 
Introduction
IntroductionIntroduction
Introduction
sarojbhavaraju5
 
Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)
MUHAMMAD AAMIR
 
Dbms Useful PPT
Dbms Useful PPTDbms Useful PPT
Dbms Useful PPT
Krishna Bashyal
 
Db lecture 2
Db lecture 2Db lecture 2
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfChapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Axmedcarb
 
Database Systems - introduction
Database Systems - introductionDatabase Systems - introduction
Database Systems - introduction
Jananath Banuka
 
Database, Lecture-1.ppt
Database, Lecture-1.pptDatabase, Lecture-1.ppt
Database, Lecture-1.ppt
MatshushimaSumaya
 
Lect 1-2 Zaheer Abbas
Lect 1-2 Zaheer AbbasLect 1-2 Zaheer Abbas
Lect 1-2 Zaheer Abbas
Information Technology Center
 
Data structure (basics)
Data structure (basics)Data structure (basics)
Data structure (basics)
ShrushtiGole
 
IMPORTANT QUESTIONS OF Data Base Management System MGU
IMPORTANT QUESTIONS OF Data Base Management System MGUIMPORTANT QUESTIONS OF Data Base Management System MGU
IMPORTANT QUESTIONS OF Data Base Management System MGU
aljufmuhammad
 
Datastructures Notes
Datastructures NotesDatastructures Notes
Datastructures Notes
Ranjithkumar C
 
Database Concepts
Database ConceptsDatabase Concepts
Database Concepts
Upendra Reddy Vuyyuru
 
DBMS and its Models
DBMS and its ModelsDBMS and its Models
DBMS and its Models
AhmadShah Sultani
 
Lect 1-2
Lect 1-2Lect 1-2
Lect 1-2
Zaheer Aghani
 
Data Structures: Classification of Data Structures
Data Structures: Classification of Data StructuresData Structures: Classification of Data Structures
Data Structures: Classification of Data Structures
Navya Francis
 
Lesson 1 - Data Structures and Algorithms Overview.pdf
Lesson 1 - Data Structures and Algorithms Overview.pdfLesson 1 - Data Structures and Algorithms Overview.pdf
Lesson 1 - Data Structures and Algorithms Overview.pdf
LeandroJrErcia
 
Dbms architecture
Dbms architectureDbms architecture
Dbms architecture
Shubham Dwivedi
 
Midterm revision - without answer edit.pdf
Midterm revision - without answer edit.pdfMidterm revision - without answer edit.pdf
Midterm revision - without answer edit.pdf
AhmedSalah48055
 
IT6701-Information management question bank
IT6701-Information management question bankIT6701-Information management question bank
IT6701-Information management question bank
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
 

Similar to Data Structure using C by Dr. K Adisesha .ppsx (20)

DS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxDS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptx
 
Introduction
IntroductionIntroduction
Introduction
 
Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)
 
Dbms Useful PPT
Dbms Useful PPTDbms Useful PPT
Dbms Useful PPT
 
Db lecture 2
Db lecture 2Db lecture 2
Db lecture 2
 
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfChapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdf
 
Database Systems - introduction
Database Systems - introductionDatabase Systems - introduction
Database Systems - introduction
 
Database, Lecture-1.ppt
Database, Lecture-1.pptDatabase, Lecture-1.ppt
Database, Lecture-1.ppt
 
Lect 1-2 Zaheer Abbas
Lect 1-2 Zaheer AbbasLect 1-2 Zaheer Abbas
Lect 1-2 Zaheer Abbas
 
Data structure (basics)
Data structure (basics)Data structure (basics)
Data structure (basics)
 
IMPORTANT QUESTIONS OF Data Base Management System MGU
IMPORTANT QUESTIONS OF Data Base Management System MGUIMPORTANT QUESTIONS OF Data Base Management System MGU
IMPORTANT QUESTIONS OF Data Base Management System MGU
 
Datastructures Notes
Datastructures NotesDatastructures Notes
Datastructures Notes
 
Database Concepts
Database ConceptsDatabase Concepts
Database Concepts
 
DBMS and its Models
DBMS and its ModelsDBMS and its Models
DBMS and its Models
 
Lect 1-2
Lect 1-2Lect 1-2
Lect 1-2
 
Data Structures: Classification of Data Structures
Data Structures: Classification of Data StructuresData Structures: Classification of Data Structures
Data Structures: Classification of Data Structures
 
Lesson 1 - Data Structures and Algorithms Overview.pdf
Lesson 1 - Data Structures and Algorithms Overview.pdfLesson 1 - Data Structures and Algorithms Overview.pdf
Lesson 1 - Data Structures and Algorithms Overview.pdf
 
Dbms architecture
Dbms architectureDbms architecture
Dbms architecture
 
Midterm revision - without answer edit.pdf
Midterm revision - without answer edit.pdfMidterm revision - without answer edit.pdf
Midterm revision - without answer edit.pdf
 
IT6701-Information management question bank
IT6701-Information management question bankIT6701-Information management question bank
IT6701-Information management question bank
 

More from Prof. Dr. K. Adisesha

Operating System-4 "File Management" by Adi.pdf
Operating System-4 "File Management" by Adi.pdfOperating System-4 "File Management" by Adi.pdf
Operating System-4 "File Management" by Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System-3 "Memory Management" by Adi.pdf
Operating System-3 "Memory Management" by Adi.pdfOperating System-3 "Memory Management" by Adi.pdf
Operating System-3 "Memory Management" by Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System Concepts Part-1 by_Adi.pdf
Operating System Concepts Part-1 by_Adi.pdfOperating System Concepts Part-1 by_Adi.pdf
Operating System Concepts Part-1 by_Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System-2_Process Managementby_Adi.pdf
Operating System-2_Process Managementby_Adi.pdfOperating System-2_Process Managementby_Adi.pdf
Operating System-2_Process Managementby_Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Prof. Dr. K. Adisesha
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
Prof. Dr. K. Adisesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdf
Prof. Dr. K. Adisesha
 
Introduction to Computers.pdf
Introduction to Computers.pdfIntroduction to Computers.pdf
Introduction to Computers.pdf
Prof. Dr. K. Adisesha
 
R_Programming.pdf
R_Programming.pdfR_Programming.pdf
R_Programming.pdf
Prof. Dr. K. Adisesha
 
Scholarship.pdf
Scholarship.pdfScholarship.pdf
Scholarship.pdf
Prof. Dr. K. Adisesha
 
Operating System-2 by Adi.pdf
Operating System-2 by Adi.pdfOperating System-2 by Adi.pdf
Operating System-2 by Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System-1 by Adi.pdf
Operating System-1 by Adi.pdfOperating System-1 by Adi.pdf
Operating System-1 by Adi.pdf
Prof. Dr. K. Adisesha
 

More from Prof. Dr. K. Adisesha (20)

Operating System-4 "File Management" by Adi.pdf
Operating System-4 "File Management" by Adi.pdfOperating System-4 "File Management" by Adi.pdf
Operating System-4 "File Management" by Adi.pdf
 
Operating System-3 "Memory Management" by Adi.pdf
Operating System-3 "Memory Management" by Adi.pdfOperating System-3 "Memory Management" by Adi.pdf
Operating System-3 "Memory Management" by Adi.pdf
 
Operating System Concepts Part-1 by_Adi.pdf
Operating System Concepts Part-1 by_Adi.pdfOperating System Concepts Part-1 by_Adi.pdf
Operating System Concepts Part-1 by_Adi.pdf
 
Operating System-2_Process Managementby_Adi.pdf
Operating System-2_Process Managementby_Adi.pdfOperating System-2_Process Managementby_Adi.pdf
Operating System-2_Process Managementby_Adi.pdf
 
Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdf
 
Introduction to Computers.pdf
Introduction to Computers.pdfIntroduction to Computers.pdf
Introduction to Computers.pdf
 
R_Programming.pdf
R_Programming.pdfR_Programming.pdf
R_Programming.pdf
 
Scholarship.pdf
Scholarship.pdfScholarship.pdf
Scholarship.pdf
 
Operating System-2 by Adi.pdf
Operating System-2 by Adi.pdfOperating System-2 by Adi.pdf
Operating System-2 by Adi.pdf
 
Operating System-1 by Adi.pdf
Operating System-1 by Adi.pdfOperating System-1 by Adi.pdf
Operating System-1 by Adi.pdf
 

Recently uploaded

bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
Sarojini38
 
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT KanpurDiversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Quiz Club IIT Kanpur
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
Kalna College
 
Observational Learning
Observational Learning Observational Learning
Observational Learning
sanamushtaq922
 
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
ShwetaGawande8
 
Diversity Quiz Prelims by Quiz Club, IIT Kanpur
Diversity Quiz Prelims by Quiz Club, IIT KanpurDiversity Quiz Prelims by Quiz Club, IIT Kanpur
Diversity Quiz Prelims by Quiz Club, IIT Kanpur
Quiz Club IIT Kanpur
 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapitolTechU
 
Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024
khabri85
 
How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17
Celine George
 
8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity
RuchiRathor2
 
nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...
chaudharyreet2244
 
How to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRMHow to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRM
Celine George
 
CIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdfCIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdf
blueshagoo1
 
Interprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdfInterprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdf
Ben Aldrich
 
How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17
Celine George
 
How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...
Infosec
 
Information and Communication Technology in Education
Information and Communication Technology in EducationInformation and Communication Technology in Education
Information and Communication Technology in Education
MJDuyan
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
OH TEIK BIN
 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Kalna College
 
Creation or Update of a Mandatory Field is Not Set in Odoo 17
Creation or Update of a Mandatory Field is Not Set in Odoo 17Creation or Update of a Mandatory Field is Not Set in Odoo 17
Creation or Update of a Mandatory Field is Not Set in Odoo 17
Celine George
 

Recently uploaded (20)

bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
 
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT KanpurDiversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT Kanpur
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
 
Observational Learning
Observational Learning Observational Learning
Observational Learning
 
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
 
Diversity Quiz Prelims by Quiz Club, IIT Kanpur
Diversity Quiz Prelims by Quiz Club, IIT KanpurDiversity Quiz Prelims by Quiz Club, IIT Kanpur
Diversity Quiz Prelims by Quiz Club, IIT Kanpur
 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
 
Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024
 
How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17
 
8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity
 
nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...
 
How to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRMHow to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRM
 
CIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdfCIS 4200-02 Group 1 Final Project Report (1).pdf
CIS 4200-02 Group 1 Final Project Report (1).pdf
 
Interprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdfInterprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdf
 
How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17
 
How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...
 
Information and Communication Technology in Education
Information and Communication Technology in EducationInformation and Communication Technology in Education
Information and Communication Technology in Education
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
 
Creation or Update of a Mandatory Field is Not Set in Odoo 17
Creation or Update of a Mandatory Field is Not Set in Odoo 17Creation or Update of a Mandatory Field is Not Set in Odoo 17
Creation or Update of a Mandatory Field is Not Set in Odoo 17
 

Data Structure using C by Dr. K Adisesha .ppsx

  • 1. Data Structures using C Prof. Dr. K ADISESHA
  • 2. Please bring to class each day Introduction Types of Data structures Arrays Stacks and Queues Linked lists 2 Data Structures Trees
  • 3. Introduction Prof. Dr. K. Adisesha 3 Data Structures: Data  Data is a collection of facts, numbers, letters or symbols that the computer process into meaningful information. Data structure  Data structure is representation of the logical relationship existing between individual elements of data.  Data structure is a specialized format for organizing and storing data in memory that considers not only the elements stored but also their relationship to each other.
  • 4. Introduction Prof. Dr. K. Adisesha 4 Why to Learn Data Structure: As applications are getting complex and data rich, there are three common problems that applications face now-a-days  Data Search − Consider an inventory of 1 million(106) items of a store. If the application is to search an item, it has to search an item in 1 million(106) items every time slowing down the search. As data grows, search will become slower.  Processor speed − Processor speed although being very high, falls limited if the data grows to billion records.  Multiple requests − As thousands of users can search data simultaneously on a web server, even the fast server fails while searching the data..
  • 5. Introduction Prof. Dr. K. Adisesha 5 Data Structures: Data structures are essential components that help organize and store data efficiently in computer memory.  They provide a way to manage and manipulate data effectively, enabling faster access, insertion, and deletion operations.
  • 6. Introduction Prof. Dr. K. Adisesha 6 Data Type: Data type is a way to classify various types of data which determines the values that can be used with the corresponding type of data, the type of operations that can be performed on the corresponding type of data. There are two data types:  Built-in Data Type: Those data types for which a language has built-in support are known as Built-in Data type.  Derived Data Type: Those data types which are implementation independent as they can be implemented in one or the other way are known as derived data types.
  • 7. Data Structures Prof. Dr. K. Adisesha 7 Classification of Data Structure using C: Data structure are normally divided into two broad categories:  Primitive Data Structure  Non-Primitive Data Structure  Linear Data Structure  Non-Linear Data Structure
  • 8. Data Structures Prof. K. Adisesha 8 Differences between Data Structure: The most commonly used differences between on data structure are broadly categorized into following types:  A primitive data structure is generally a basic structure that is usually built into the language, such as an integer, a float.  A non-primitive data structure is built out of primitive data structures linked together in meaningful ways, such as a or a linked-list, binary search tree, AVL Tree, graph etc.
  • 9. Data Structures Prof. Dr. K. Adisesha 9 Primitive Data Structure: Data structures that are directly operated upon the machine-level instructions are known as primitive data structures:  There are basic structures and directly operated upon by the machine instructions.  The Data structures that fall in this category are.  Integer  Floating-point number  Character constants  string constants  pointers etc.,
  • 10. Data Structures Prof. Dr. K. Adisesha 10 Primitive Data Structure: Data structures that are directly operated upon the machine-level instructions are known as primitive data structures:  The most commonly used operation on data structure are broadly categorized into following types:  Create  Insertion  Selection  Updating  Destroy or Delete
  • 11. Data Structures Prof. Dr. K. Adisesha 11 Non-Primitive Data Structure: The Data structures that are derived from the primitive data structures are called Non- primitive data structure:  There are more sophisticated data structures  The non-primitive data structures emphasize on structuring of a group of homogeneous (same type) or heterogeneous (different type) data items:  Linear Data structures  Non-Linear Data structures
  • 12. Data Structures Prof. Dr. K. Adisesha 12 Non-Primitive Data Structure: Linear Data structures Linear Data structures are kind of data structure that has homogeneous elements.  The data structure in which elements are in a sequence and form a liner series.  Linear data structures are very easy to implement, since the memory of the computer is also organized in a linear fashion.  Some commonly used linear data structures are:  Stack  Queue  Linked Lists
  • 13. Data Structures Prof. Dr. K. Adisesha 13 Non-Primitive Data Structure: Non-Linear Data structures A Non-Linear Data structures is a data structure in which data item is connected to several other data items.  Non-Linear data structure may exhibit either a hierarchical relationship or parent child relationship.  The data elements are not arranged in a sequential structure.  Some commonly used non-linear data structures are:  Trees  Graphs
  • 14. Data Structures Prof. Dr. K. Adisesha 14 Non-Primitive Data Structure: The most commonly used operation on data structure are broadly categorized into following types:  Traversal  Insertion  Selection  Searching  Sorting  Merging  Destroy or Delete
  • 15. Memory Allocation Prof. Dr. K. Adisesha 15 Memory Allocation in C: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space.  The Memory is divided into three sections.  Heap Memory: It is a part of the main memory. It is unorganized and treated as a resource when you require the use of it if not release.  Stack Memory: It stores temporary variables created by a function. In stack, variables are declared, stored, and initialized during runtime.  Code Section: Whenever the program is executed it will be brought into the main memory. This program will get stored under the code section.
  • 16. Memory Allocation Prof. Dr. K. Adisesha 16 Memory Allocation in C: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space.  The memory allocation is done either before or at the time of program execution.  There are two types of memory allocations:  Compile-time or Static Memory Allocation: Memory is allocated for declared variables by the compiler.  Run-time or Dynamic Memory Allocation: Memory allocation done at the time of execution(run time) is known as dynamic memory allocation.
  • 17. Memory Allocation Prof. Dr. K. Adisesha 17 Static Memory Allocation in C: In static memory allocation the program executes fixes the size that the program is going to take, and it can’t be changed further. So, the exact memory requirements must be known before.  Allocation and deallocation of memory will be done by the compiler automatically.  Key Features:  Allocation and deallocation are done by the compiler.  It uses a data structures stack for static memory allocation.  Variables get allocated permanently.  Execution is faster than dynamic memory allocation.  Memory is allocated before runtime.
  • 18. Memory Allocation Prof. Dr. K. Adisesha 18 Dynamic Memory Allocation in C: In Dynamic memory allocation size initialization and allocation are done by the programmer. It is managed and served with pointers that point to the newly allocated memory space in an area which we call the heap.  Heap memory is unorganized and it is treated as a resource when you require the use of it if not release it.  Key Features:  Dynamic allocated at runtime  We can also reallocate memory size if needed.  Dynamic Allocation is done at run time.  No memory wastage
  • 19. Memory Allocation Prof. Dr. K. Adisesha 19 Dynamic Memory Allocation in C: There are some functions available in the stdlib.h header which will help to allocate memory dynamically.  malloc(): function allocates memory at runtime is called malloc() function returns a pointer with the value NULL. Syntax: int *p = (int*)malloc(No of values*size(int));  calloc(): function initializes the memory that is allocated so that all bytes are zero. Syntax: int *p = (int*)calloc(Number of data items, sizeof(int));  realloc(): The realloc() function enables you to reuse or extend the memory that you previously allocated using malloc() or calloc(). Syntax: int *np = (type cast) realloc (pointer type, number of elements * sizeof(int));  free(): When memory is allocated dynamically it should always be released when it is no longer required. Syntax: free(pointer);
  • 20. Data Structures Prof. Dr. K. Adisesha 20 Algorithms and Applications of Data Structures: Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. Algorithms are generally created independent of underlying languages.  From the data structure point of view, following are some important categories of algorithms.  Insert − Algorithm to insert item in a data structure.  Traverse − Algorithm to visit every item in a data structure.  Update − Algorithm to update an existing item in a data structure.  Search − Algorithm to search an item in a data structure.  Sort − Algorithm to sort items in a certain order.  Delete − Algorithm to delete an existing item from a data structure.
  • 21. Algorithm Prof. Dr. K. Adisesha 21 Characteristics of an Algorithm: An algorithm should have the following characteristics −.  Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning.  Input − An algorithm should have 0 or more well-defined inputs.  Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output.  Finiteness − Algorithms must terminate after a finite number of steps.  Feasibility − Should be feasible with the available resources.  Independent − An algorithm should have step-by-step directions, which should be independent of any programming code.
  • 22. Algorithm Prof. Dr. K. Adisesha 22 Characteristics of a Data Structure: Data Structure is a systematic way to organize data in order to use it efficiently. Following terms are the Characteristics of a data structure.  Correctness − Data structure implementation should implement its interface correctly.  Time Complexity − Running time or the execution time of operations of data structure must be as small as possible.  Space Complexity − Memory usage of a data structure operation should be as little as possible.
  • 23. Algorithm Prof. Dr. K. Adisesha 23 Algorithm Analysis: Efficiency of an algorithm can be analyzed at two different stages, before implementation and after implementation. They are the following .  A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an algorithm is measured by assuming factors, like processor speed, are constant and have no effect on the implementation.  A Posterior Analysis − This is an empirical analysis of an algorithm. The selected algorithm is implemented using programming language. In this analysis, actual statistics like running time and space required, are collected.
  • 24. Algorithm Prof. Dr. K. Adisesha 24 Algorithm Complexity: The complexity of an algorithm represents the amount of memory space and time required by the algorithm in its life cycle.  Space complexity − Space complexity of an algorithm represents the amount of memory space required by the algorithm in its life cycle..  Time complexity − Time complexity of an algorithm represents the amount of time required by the algorithm to run to completion.
  • 25. Algorithm  Calculate  Lines 1 and 4 count for one unit each  Line 3: executed N times, each time four units  Line 2: (1 for initialization, N+1 for all the tests, N for all the increments) total 2N + 2  total cost: 6N + 4  O(N)   N i i 1 3 1 2 3 4 1 2N+2 4N 1
  • 26. Algorithm Prof. Dr. K. Adisesha 26 Asymptotic Analysis of an algorithm: Asymptotic analysis of an algorithm refers to Asymptotic analysis refers to computing the running time of any operation in mathematical units of computation of its run-time performance.  The Asymptotic analysis of an algorithm falls under three types:  Best Case − Minimum time required for program execution.  Average Case − Average time required for program execution.  Worst Case − Maximum time required for program execution.
  • 27. Algorithm Prof. Dr. K. Adisesha 27 Asymptotic Notations of an algorithm: Following are the commonly used asymptotic notations to calculate the running time complexity of an algorithm..  The Asymptotic Notations of an algorithm falls under three types:  Big Oh Notation, Ο− It measures the worst case time complexity.  Omega Notation, Ω− It measures the best case time complexity.  Theta Notation, θ− It measures the Average case time complexity.
  • 28. Algorithm Prof. Dr. K. Adisesha 28 Big Oh Notation, ( Ο )of an algorithm: The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time.  It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete.  For example, for a function f(n)  It is represented as follows  Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0. }
  • 29. Algorithm Prof. Dr. K. Adisesha 29 Omega Notation, Ω of an algorithm: The notation Ω(n) is the formal way to express the lower bound of an algorithm's running time. It measures the best case time complexity or the best amount of time an algorithm can possibly take to complete • For example, for a function f(n) • It is represented as follows • Ω(f(n)) ≥ { g(n) : there exists c > 0 and n0 such that g(n) ≤ c.f(n) for all n > n0. }
  • 30. Algorithm Prof. Dr. K. Adisesha 30 Theta Notation, θ of an algorithm: The notation θ(n) is the formal way to express both the lower bound and the upper bound of an algorithm's running time.  For example, for a function f(n)  It is represented as follows  θ(f(n)) = { g(n) if and only if g(n) = Ο(f(n)) and g(n) = Ω(f(n)) for all n > n0. }
  • 31. Algorithm Prof. Dr. K. Adisesha 31 Common Asymptotic Notations: Following is a list of some common asymptotic notations.  constant − Ο(1)  logarithmic− Ο(log n)  linear − Ο(n)  n log n − Ο(n log n)  quadratic − Ο(n2)  cubic − Ο(n3)  polynomial − nΟ(1)  exponential− 2Ο(n)
  • 32. Recursion Prof. Dr. K. Adisesha 32 Recursion: Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.  while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.  Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.
  • 33. Recursion Prof. Dr. K. Adisesha 33 Recursion: Recursion is the process in which a function calls itself up to n-number of times. If a program allows the user to call a function inside the same function recursively, the procedure is called a recursive call of the function.  Types of Recursion in C:  Direct Recursion  Indirect Recursion  Tail Recursion  No Tail/ Head Recursion  Linear recursion  Tree Recursion
  • 34. Recursion Prof. Dr. K. Adisesha 34 Types of the recursion: Following are the types of the recursion in C programming language, as follows:  Direct Recursion: When a function calls itself within the same function repeatedly, it is called the direct recursion.  Indirect Recursion: When a function is mutually called by another function in a circular manner, the function is called an indirect recursion function. Direct Recursion: fun() { // write some code fun(); // some code } Indirect Recursion: fun1() { // write some code fun2(); } fun2() { // write some code fun1(); // write some code }
  • 35. Recursion Prof. Dr. K. Adisesha 35 Types of the recursion: Following are the types of the recursion in C programming language, as follows:  Tail Recursion: A recursive function is called the tail-recursive if the function makes recursive calling itself, and that recursive call is the last statement executes by the function. After that, there is no function or statement is left to call the recursive function.  Head Recursion: A function is called the non-tail or head recursive if a function makes a recursive call itself, the recursive call will be the first statement in the function.  Linear recursion: A function is called the linear recursive if the function makes a single call to itself at each time the function runs and grows linearly in proportion to the size of the problem.  Tree Recursion: A function is called the tree recursion, in which the function makes more than one call to itself within the recursive function.
  • 36. Recursion Prof. Dr. K. Adisesha 36 Recursion: The C programming language supports recursion, i.e., a function to call itself.  The following example calculates the factorial of a given number using a recursive function − #include <stdio.h> int factorial(int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 12; printf("Factorial of %d is %dn", i, factorial(i)); return 0; }
  • 37. Recursion Prof. Dr. K. Adisesha 37 Drawbacks of Recursion in Data Structure: There are some potential drawbacks to using recursion in data structures, including:  Memory usage: Recursive algorithms can use a lot of memory, particularly if the recursion goes too deep or if the data structure is large. Each recursive call creates a new stack frame on the call stack, which can quickly add up to a significant amount of memory usage.  Stack overflow: If the recursion goes too deep, it can cause a stack overflow error, which can crash the program.  Performance: Recursive algorithms can be less efficient than iterative algorithms in some cases, particularly if the data structure is large or if the recursion goes too deep.  Debugging: Recursive algorithms can be more difficult to debug than iterative algorithms, particularly if the recursion goes too deep or if the program is using multiple recursive calls.  Code complexity: Recursive algorithms can be more complex than iterative algorithm.
  • 38. Recursion Prof. Dr. K. Adisesha 38 Difference between Recursion and Iteration: Basis Recursion Iteration Basis of repetition Recursion is based on the idea of a function calling itself. The base case is the simplest version of the problem that can be solved without recursion. Iteration, on the other hand, uses looping constructs such as "for" and "while" to repeat a process a certain number of times or until a specific condition is met. Control flow Recursion relies on the call stack to keep track of function calls and their parameters. Each recursive call pushes a new function call onto the call stack, and each return pops the function call off the stack. Iteration, on the other hand, does not rely on the call stack and uses variables and control structures to control the flow of execution. Performance Recursion can be more elegant and easier to understand for certain types of problems Iteration is often more efficient than recursion, especially for large datasets or complex algorithms.
  • 39. Unit -2 Arrays Prof. Dr. K. Adisesha 39 Arrays: An array is defined as a set of finite number of homogeneous elements or same data items:  Following are the important terms to understand the concept of Array.  Element − Each item stored in an array is called an element.  Index − Each location of an element in an array has a numerical index, which is used to identify the element.  Declaration of array is as follows:  Syntax: Datatype Array_Name [Size];  Example: int arr[10];  Where int specifies the data type or type of elements arrays stores.  “arr” is the name of array & the number specified inside the square brackets is the number of elements an array can store, this is also called sized or length of array.
  • 40. Arrays Prof. Dr. K. Adisesha 40 Arrays: Represent a Linear Array in memory:  The elements of linear array are stored in consecutive memory locations.  It is shown below: int A[5]={23, 4, 6, 15, 5, 7}
  • 41. Arrays Prof. Dr. K. Adisesha 41 Calculating the length of the array: The elements of array will always be stored in the consecutive (continues) memory location.  The number of elements that can be stored in an array, that is the size of array or its length is given by the following equation: o A[n] is the array size or length of n elements. o The length of the array can be calculated by: L = UB – LB + 1 o To Calculate the address of any element in array: Loc(A[P])=Base(A)+W(P-LB) o Here, UB is the largest Index and LB is the smallest index  Example: If an array A has values 10, 20, 30, 40, 50, stored in location 0,1, 2, 3, 4 the UB = 4 and LB=0 Size of the array L = 4 – 0 + 1 = 5
  • 42. Arrays Prof. Dr. K. Adisesha 42 Types of Arrays: The elements of array will always be stored in the consecutive (continues) memory location. The various types of Arrays are:  Single Dimension Array:  Array with one subscript  Ex: int A[i];  Two Dimension Array  Array with two subscripts (Rows and Column)  Ex: int A[i][j];  Multi Dimension Array:  Array with Multiple subscripts  Ex: int A[i][j]..[n];
  • 43. Arrays Prof. Dr. K. Adisesha 43 Abstract Data Type: ADTs or abstract data types are the ways of classifying data structures by providing a minimal expected interface and some set of methods.  Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of values and a set of operations.  Abstract data types (ADTs) are a way of encapsulating data and operations on that data into a single unit.  Array as ADT (Abstract Data Type) mean data structure array and the set of operations:  Representation of Data.  Set of Operations on the Data.
  • 44. Arrays Prof. Dr. K. Adisesha 44 Basic operations of Arrays: Some common operation performed on array are:  Traversing  Insertion  Deletion  Searching  Sorting  Merging
  • 45. Arrays Prof. Dr. K. Adisesha 45 Traversing Arrays: Traversing: It is used to access each data item exactly once so that it can be processed:  We have linear array A as below: 1 2 3 4 5 10 20 30 40 50  Here we will start from beginning and will go till last element and during this process we will access value of each element exactly once as below: A [0] = 10 A [1] = 20 A [2] = 30 A [3] = 40 A [4] = 50
  • 46. Arrays Prof. Dr. K. Adisesha 46 Traverse Operation: Following program traverses and prints the elements of an array:
  • 47. Arrays Prof. Dr. K. Adisesha 47 Insertion into Array: Insertion: It is used to add a new data item in the given collection of data items:  We have linear array A as below: 1 2 3 4 5 10 20 50 30 15  New element to be inserted is 100 and location for insertion is 3.  So shift the elements from 5th location to 3rd location downwards by 1 place.  And then insert 100 at 3rd location
  • 48. Arrays Prof. Dr. K. Adisesha 48 Insertion into Array: Insertion into Array:  Insertion 100 into Array at Pos=3 A [0] = 10 A [1] = 20 A [2] = 50 A [3] = 30 A [4] = 15
  • 49. Arrays Prof. Dr. K. Adisesha 49 Insertion into Array: Add a new data item in the given array of data: Insertion into Array: A [0] = 1 A [1] = 3 A [2] = 5 A [3] = 7 A [4] = 8
  • 50. Arrays Prof. Dr. K. Adisesha 50 Deletion from Array: Deletion: It is used to delete an existing data item from the given collection of data items:  Deletion 30 from Array at Pos 3 A [0] = 10 A [1] = 20 A [2] = 30 A [3] = 40 A [4] = 50
  • 51. Arrays Prof. Dr. K. Adisesha 51 Deletion from Array: A [0] = 1 A [1] = 3 A [2] = 5 A [3] = 7 A [4] = 8
  • 52. Arrays Searching Prof. Dr. K. Adisesha 52 Searching in Arrays: Searching: It is used to find out the location of the data item if it exists in the given collection of data items:  E.g. We have linear array A as below: 1 2 3 4 5 10 20 50 30 35  Suppose item to be searched is 35. We will start from beginning and will compare 35 with each element.  This process will continue until element is found or array is finished.  Types of searching Algorithms:  Linear searching  Binary Searching
  • 53. Arrays Searching Prof. Dr. K. Adisesha 53 Linear search: Linear Searching: Also called Sequential Searching.  It is used to find out the location of the data item if it exists in the given collection of data items.  Example Searching element 33 from the array of elements:
  • 54. Arrays Searching Prof. Dr. K. Adisesha 54 Linear search: Linear Searching: Also called Sequential Searching.
  • 55. Arrays Searching Prof. Dr. K. Adisesha 55 Binary Searching: The binary search algorithm can be used with only sorted list of elements.  Binary Search first divides a large array into two smaller sub-arrays and then recursively operate the sub-arrays.  Binary Search basically reduces the search space to half at each step
  • 56. Arrays Searching Prof. Dr. K. Adisesha 56 Binary Searching: The binary search algorithm can be used with only sorted list of elements.  Example: Searching the element 57 from the array of elements
  • 57. Arrays Searching Prof. Dr. K. Adisesha 57 Binary Searching:  Example:
  • 58. Arrays Searching Prof. Dr. K. Adisesha 58 Binary Searching:
  • 59. Arrays Searching Prof. Dr. K. Adisesha 59 Difference in Searching:
  • 60. Arrays Searching Prof. Dr. K. Adisesha 60 Difference in Searching:
  • 61. Arrays Sorting Prof. Dr. K. Adisesha 61 Sorting in Arrays: A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements:  The comparison operator is used to decide the new order of element in the respective data structure.  Types of Sorting Algorithms are:  Bubble Sort  Insertion Sort  Selection Sort  Merge Sort  Quick Sort  Heap Sort  Radix Sort  Bucket Sort  Shell Sort
  • 62. Arrays Sorting Prof. Dr. K. Adisesha 62 Bubble Sort in Arrays: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
  • 63. Arrays Sorting Prof. Dr. K. Adisesha 63 Bubble Sort in Arrays: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. Algorithm begin BubbleSort(arr) for all array elements if arr[i] > arr[i+1] swap(arr[i], arr[i+1]) end if end for return arr end BubbleSort
  • 64. Arrays Sorting Prof. Dr. K. Adisesha 64 Insertion Sorting: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time.  This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted.
  • 65. Arrays Sorting Prof. Dr. K. Adisesha 65 Insertion Sorting: This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted.  This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted.
  • 66. Arrays Sorting Prof. Dr. K. Adisesha 66 Insertion Sorting:  ALGORITHM: Insertion Sort (A, N) A is an array with N unsorted elements.  Step 1: for I=1 to N-1  Step 2: J = I While(J >= 1) if ( A[J] < A[J-1] ) then Temp = A[J]; A[J] = A[J-1]; A[J-1] = Temp; [End if] J = J-1 [End of While loop] [End of For loop]  Step 3: Exit
  • 67. Arrays Sorting Prof. Dr. K. Adisesha 67 Selection Sort: Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.  To implement the Selection Sort algorithm, we need:  An array with values to sort.  An inner loop that goes through the array, finds the lowest value, and moves it to the front of the array. This loop must loop through one less value each time it runs.  An outer loop that controls how many times the inner loop must run. For an array with n  values, this outer loop must run n−1 times.
  • 68. Arrays Sorting Prof. Dr. K. Adisesha 68 Selection Sort:
  • 69. Arrays Sorting Prof. Dr. K. Adisesha 69 Selection Sort:
  • 70. Arrays Sorting Prof. Dr. K. Adisesha 70 Merge Sort Algorithm: Merge sort is a sorting technique based on divide and conquer technique. Merge sort first divides the array into equal halves and then combines them in a sorted manner.  Here’s a step-by-step explanation of how merge sort works:  Divide: Divide the list or array recursively into two halves until it can no more be divided.  Conquer: Each subarray is sorted individually using the merge sort algorithm.  Merge: The sorted subarrays are merged back together in sorted order. The process continues until all elements from both subarrays have been merged.
  • 71. Arrays Sorting Prof. Dr. K. Adisesha 71 Merging from Array: Merging: It is used to combine the data items of two sorted files into single file in the sorted form.  We have sorted linear array A as below: 1 2 3 4 5 6 10 40 50 80 95 100  And sorted linear array B as below: 1 2 3 4 20 35 45 90  After merging merged array C is as below: 1 2 3 4 5 6 7 8 9 10 10 20 35 40 45 50 80 90 95 100
  • 72. Arrays Sorting Prof. Dr. K. Adisesha 72 Quicksort: Quicksort is one of the fastest sorting algorithms. This algorithm takes an array of values, chooses one of the values as the 'pivot' element, and moves the other values so that lower values are on the left and higher values are on the right of pivot element.  The algorithm can be described like this:  Choose a value in the array to be the pivot element.  Order the rest of the array so that lower values than the pivot element are on the left, and higher values are on the right.  Swap the pivot element with the first element of the higher values so that the pivot element lands in between the lower and higher values.  Do the same operations (recursively) for the sub-arrays on the left and right side of the pivot element.
  • 73. Arrays Sorting 73 Quicksort Algorithms : Prof. Dr. K. Adisesha
  • 74. Arrays Sorting 74 Quicksort Algorithms : Prof. Dr. K. Adisesha
  • 75. Arrays Sorting 75 Complexity of Sorting Algorithms : Prof. Dr. K. Adisesha
  • 76. Arrays Prof. Dr. K. Adisesha 76 Two dimensional array: A two dimensional array is a collection of elements and each element is identified by a pair of subscripts. ( A[3] [3] ).  The elements are stored in continuous memory locations.  The elements of two-dimensional array as rows and columns.  The number of rows and columns in a matrix is called as the order of the matrix and denoted as MxN.  The number of elements can be obtained by multiplying number of rows and number of columns. A[0] A[1] A[2] A[0] 10 20 30 A[1] 40 50 60 A[2] 70 80 90
  • 77. Arrays Prof. Dr. K. Adisesha 77 Representation of Two Dimensional Array: A two dimensional array is a collection of elements and each element is identified by a pair of subscripts. ( A[m] [n] )  A is the array of order m x n. To store m*n number of elements, we need m*n memory locations.  The elements should be in contiguous memory locations.  There are two methods:  Row-major method  Column-major method A[0] A[1] A[2] A[0] 10 20 30 A[1] 40 50 60 A[2] 70 80 90
  • 78. Arrays Prof. Dr. K. Adisesha 78 Representation of Two Dimensional Array: Row-Major Method:  All the first-row elements are stored in sequential memory locations and then all the second-row elements are stored and so on. Ex: A[Row][Col] Column-Major Method:  All the first column elements are stored in sequential memory locations and then all the second-column elements are stored and so on. Ex: A [Col][Row] 1000 10 A[0][0] 1002 20 A[0][1] 1004 30 A[0][2] 1006 40 A[1][0] 1008 50 A[1][1] 1010 60 A[1][2] 1012 70 A[2][0] 1014 80 A[2][1] 1016 90 A[2][2] 1000 10 A[0][0] 1002 40 A[1][0] 1004 70 A[2][0] 1006 20 A[0][1] 1008 50 A[1][1] 1010 80 A[2][1] 1012 30 A[0][2] 1014 60 A[1][2] 1016 90 A[2][2] Row-Major Method Col-Major Method
  • 79. Arrays Prof. Dr. K. Adisesha 79 Calculating the length of the 2D-Array : A two dimensional array is a collection of elements and each element is identified by a pair of subscripts. ( A[m] [n] )  The size of array or its length is given by the following equation: A[i][j] is the array size or length of m*n elements.  To Calculate the address of i*j th element in array:  Row-Major Method: Loc(A[i][j])=Base(A)+W[n(i-LB)+(j-LB)]  Col-Major Method: Loc(A[i][j])=Base(A)+W[(i-LB)+m(j-LB)] Here, W is the number of words per memory location and LB is the smallest index
  • 80. Arrays Prof. Dr. K. Adisesha 80 Sparse matrix: Sparse matrices are those matrices that have the majority of their elements equal to zero.  In other words, the sparse matrix can be defined as the matrix that has a greater number of zero elements than the non-zero elements.  Representing a sparse matrix by a 2D array leads to the wastage of lots of memory. In 2D array representation of sparse matrix, there are three fields used that are named as -
  • 81. Arrays Prof. Dr. K. Adisesha 81 Advantages of Array : A two dimensional array is a collection of elements and each element is identified by a pair of subscripts. ( A[m] [n] )  It is used to represent multiple data items of same type by using single name.  It can be used to implement other data structures like linked lists, stacks, queues, tree, graphs etc.  Two-dimensional arrays are used to represent matrices.  Many databases include one-dimensional arrays whose elements are records.
  • 82. Arrays Prof. Dr. K. Adisesha 82 Disadvantages of Array: A two dimensional array is a collection of elements and each element is identified by a pair of subscripts. ( A[m] [n] )  We must know in advance the how many elements are to be stored in array.  Array is static structure. It means that array is of fixed size. The memory which is allocated to array cannot be increased or decreased.  Array is fixed size; if we allocate more memory than requirement then the memory space will be wasted.  The elements of array are stored in consecutive memory locations. So insertion and deletion are very difficult and time consuming.
  • 83. Unit 3 Linked List Prof. Dr. K. Adisesha 83 Lists (linked list): A lists (Linear linked list) can be defined as a collection of variable number of data items called nodes.  Lists are the most commonly used non-primitive data structures.  Each nodes is divided into two parts:  The first part contains the information of the element.  The second part contains the memory address of the next node in the list. Also called Link part.
  • 84. Linked List Prof. Dr. K. Adisesha 84 Lists (linked list): Types of linked lists:  Single linked list  Doubly linked list  Single circular linked list  Doubly circular linked list
  • 85. Linked List Prof. Dr. K. Adisesha 85 Single linked list: The link field of the last node contains the memory address of the first node, such a linked list is called circular linked list:  The information field contains the data of that node.  The link field contains the memory address of the next node.  The last link field contains the memory address as null ().  There is only one link field in each node, the linked list is called singly linked list.
  • 86. Linked List Prof. Dr. K. Adisesha 86 Single circular linked list: A singly linked list contains two fields in each node - an information field and the linked field:  The information field contains the data of that node.  The link field contains the memory address of the next node  The last link field contains the memory address of the first node.  In a circular linked list every node is accessible from a given node.
  • 87. Linked List Prof. Dr. K. Adisesha 87 Doubly linked list: It is a linked list in which each node is points both to the next node and also to the previous node:  In doubly linked list each node contains three parts:  FORW : It is a pointer field that contains the address of the next node  BACK: It is a pointer field that contains the address of the previous node.  INFO: It contains the actual data.  In the first node, if BACK contains NULL, it indicated that it is the first node in the list.  The in which FORW contains, NULL indicates that the node is the last node.
  • 88. Linked List Prof. Dr. K. Adisesha 88 Doubly circular linked list: It is a linked list in which each node is points both to the next node and also to the previous node:  In doubly linked list each node contains three parts:  FORW : It is a pointer field that contains the address of the next node  BACK: It is a pointer field that contains the address of the previous node.  INFO: It contains the actual data.
  • 89. Linked List Prof. Dr. K. Adisesha 89 Operation on Linked List: The operation that are performed on linked lists are:  Creating a linked list  Traversing a linked list  Inserting an item into a linked list.  Deleting an item from the linked list.  Searching an item in the linked list  Merging two or more linked lists.
  • 90. Linked List Prof. Dr. K. Adisesha 90 Creating a linked list: The nodes of a linked list can be created by the following structure declaration: struct Node { int information; struct Node *link; }*node1, *node2;  Here info is the information field and link is the link field.  The link field contains a pointer variable that refers the same node structure. Such a reference is called as Self addressing pointer.
  • 91. Linked List Prof. Dr. K. Adisesha 91 Creating a linked list: The nodes of a linked list can be created by the following structure declaration:
  • 92. Linked List Prof. Dr. K. Adisesha 92 Operator new and delete: The nodes of a linked list can be created by the following structure declaration:  Operators new allocate memory space  Operators new [ ] allocates memory space for array.  Operators delete deallocate memory space.  Operators delete [ ] deallocate memory space for array. struct Node { int information; struct Node *link; }*node1, *node2;
  • 93. 93 Traversing is the process of accessing each node of the linked list exactly once to perform some operation. ALGORITHM: TRAVERS (START, P) START contains the address of the first node. Another pointer p is temporarily used to visit all the nodes from the beginning to the end of the linked list. Step 1: P = START Step 2: while P != NULL Step 3: PROCESS data (P) [Fetch the data] Step 4: P = link(P) [Advance P to next node] Step 5: End of while Step 6: Return Traversing a linked list Prof. Dr. K. Adisesha Code: struct node *temp = head; printf("nnList elements are - n"); while(temp != NULL) { printf("%d --->",temp->data); temp = temp->next; }
  • 94. 94  Inserting a node at the beginning of the linked list  Inserting a node at the given position.  Inserting a node at the end of the linked list. Linked List Inserting a node into the linked list: Prof. Dr. K. Adisesha
  • 95. 95 Linked List Inserting node at Front: Inserting a node at the beginning of the linked list 1. Create a node. 2. Fill data into the data field of the new node. 3. Mark its pointer field as NULL 4. Attach this newly created node to START 5. Make the new node as the START node. Prof. Dr. K. Adisesha
  • 96. 96 Linked List Inserting node at Front: Inserting a node at the beginning of the linked list ALGORITHM: INS_BEG (START, P) START contains the address of the first node. Step 1: P new Node; Step 2: data(P) num; Step 3: link(P) START Step 4: START P Step 5: Return Prof. Dr. K. Adisesha
  • 97. 97 Linked List Inserting node at Front: Inserting a node at the beginning of the linked list  Get the new node using getnode(). newnode = getnode();  If the list is empty then start = newnode.  If the list is not empty, follow the steps given below: newnode -> next = start; start = newnode; Prof. Dr. K. Adisesha void insert_at_beg() { node *newnode; newnode = getnode(); if(start == NULL) { start = newnode; } else { newnode -> next = start; start = newnode;} }
  • 98. 98 Linked List Inserting node at End: Inserting a node at the End of the linked list 1. Create a node. 2. Fill data into the data field of the new node. 3. Mark its pointer field as NULL 4. Attach this newly created node to Last 5. Make the new node as the Last node. Prof. Dr. K. Adisesha
  • 99. ALGORITHM: INS_END (START, P) START contains the address of the first node. Step 1: START Step 2: P START [identify the last node] while P!= null P next (P) End while Step 3: N new Node; Step 4: data(N) item; Step 5: link(N) null Step 6: link(P) N Step 7: Return 99 Inserting node at End Prof. Dr. K. Adisesha
  • 100. Insert at the End 100 Inserting node at End Prof. Dr. K. Adisesha  Allocate memory for new node  Store data  Traverse to last node  Change next of last node to recently created node struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; newNode->next = NULL; struct node *temp = head; while(temp->next != NULL){ temp = temp->next; } temp->next = newNode;
  • 101. 101 Inserting node at a given Position Inserting a node at intermediate position: Figure shows inserting a node into the single linked list at a specified intermediate position other than beginning and end. Prof. Dr. K. Adisesha
  • 102. 102 Inserting node at a given Position ALGORITHM: INS_POS (START, P1, P2) START contains the address of the first node. P2 is new node Step 1: START Step 2: P1 START [Initialize node] Count 0 Step 3: while P!= null count count+1 P1 next (P1) End while Step 4: if (POS=1) Call function INS_BEG( ) else if (POS=Count +1) Call function INS_END( ) else if (POS<=Count) P1 Start For(i=1; i<=pos; i++) P1 next(P1); end for [create] P2 new node data(P2) item; link(P2) link(P1) link(P1) P2 else PRINT “Invalid position” Step 5: Return Prof. Dr. K. Adisesha
  • 103. 103 Inserting node at a given Position Code: Insert at the Middle Prof. Dr. K. Adisesha  Allocate memory and store data for new node  Traverse to node just before the required position of new node  Change next pointers to include new node in between struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; struct node *temp = head; for(int i=2; i < position; i++) { if(temp->next != NULL) { temp = temp->next; } } newNode->next = temp->next; temp->next = newNode;
  • 104. 104 Deleting an item from the linked list:  Deletion of the first node  Deletion of the last node  Deletion of the node at the give position. Deleting an node Deleting an node: Prof. Dr. K. Adisesha
  • 105. 105 Deleting an node Deletion of the first node: This algorithm first copies data in the first node to a variable and delete the first node of the linked list. ALGORITHM: DEL_BEG(P, START) This used pointers P Step 1: START Step 2: P START; Step 3: PRINT data(P) Step 4: START Link(P) Step 5: Free(P) Step 6: STOP Prof. Dr. K. Adisesha Start = start->link;
  • 106. 106 Deleting an node Deletion of the first node: The following steps are followed, to delete a node at the beginning of the list: void delete_at_beg() { node *temp; if(start == NULL) { printf("n No nodes are exist.."); return ; } else { temp = start; start = temp -> next; free(temp); printf("n Node deleted "); } } Prof. Dr. K. Adisesha  If the list is empty, Display the empty list message  If the list is not empty, follow the steps given below: temp = start; start = start -> next; free(temp);
  • 107. 107 Deleting an node Deleting node from end: Prof. Dr. K. Adisesha The following steps are followed to delete a node at the end of the list:  If the list is not empty, follow the steps given below: temp = prev = start; while(temp -> next != NULL) { prev = temp; temp = temp -> next; } prev -> next = NULL; free(temp);
  • 108. ALGORITHM: DEL_END (P1, P2, START) This used two pointers P1 and P2. Pointer P2 is used to traverse the linked list and pointer P1 keeps the location of the previous node of P2. Step 1: START Step 2: P2 START; Step 3: while ( link(P2) ! = NULL) P1 P2 P2 link(P2) While end Step 4: PRINT data(p2) Step 5: link(P1) NULL Free(P2) Step 6: STOP 108 Deleting an node Deleting node from end: Prof. Dr. K. Adisesha
  • 109.  Traverse to second last element  Change its next pointer to null Code: struct node * temp = head; while(temp->next->next!=NULL){ temp = temp->next; } temp->next = NULL; 109 Deleting an node Deleting node from end: Prof. Dr. K. Adisesha
  • 110. Step 1: START Step 2: P1 START [Initialize node] Count 0 Step 3: while P!= null count count+1 P1 next (P1) End while Step 4: if (POS=1) Call function DEL_BEG( ) else if (POS=Count) Call function DEL_END( ) else if (POS<=Count) P2 Start For(i=1; i<=pos; i++) P1 P2 P2 link(P2) end for PRINT data(P2) link(P1) link( P2) free(P2) End if Step 5: Return 110 Deleting node at a given Position ALGORITHM: DEL_POS (START, P1, P2) START contains the address of the first node. P2 is DEL-node Prof. Dr. K. Adisesha
  • 111. 111 Deleting node at a given Position Delete from middle Prof. Dr. K. Adisesha  Traverse to element before the element to be deleted  Change next pointers to exclude the node from the chain Code: struct node* temp = head; for(int i=2; i< position; i++) { if(temp->next!=NULL) { temp = temp->next; } } temp->next = temp->next->next;
  • 112. Unit 4- Stack & Queues Prof. Dr. K. Adisesha 112 Stack: Stack is a linear data structure which follows a particular order in which the operations are performed  Insertion of element into stack is called PUSH and deletion of element from stack is called POP.  The order may be LIFO(Last In First Out) or FILO(First In Last Out).
  • 113. Stack Prof. Dr. K. Adisesha 113 Stack: Memory Representation of Stack  The stack can be implemented into two ways:  Using arrays (Static implementation)  Using pointer (Dynamic
  • 114. Stack Prof. Dr. K. Adisesha 114 Operation on Stacks: The various operation performed on Stacks are:  Stack( ): It creates a new stack that is empty. It needs no parameter and returns an empty stack.  push(item): It adds a new item to the top of the stack.  pop( ): It removes the top item from the stack.  peek( ): It returns the top item from the stack but does not remove it.  isEmpty( ): It tests whether the stack is empty.  size( ): It returns the number of items on the stack.
  • 115. Stack Prof. Dr. K. Adisesha 115 Stack Conditions: The various operation performed on Stacks depend on the following conditions:
  • 116. Stack Prof. Dr. K. Adisesha 116 PUSH Operation: The process of adding one element or item to the stack is represented by an operation called as the PUSH operation: ALGORITHM: PUSH (STACK, TOP, SIZE, ITEM) STACK is the array with N elements. TOP is the pointer to the top of the element of the array. ITEM to be inserted. Step 1: if TOP = N then [Check Overflow] PRINT “ STACK is Full or Overflow” Exit [End if] Step 2: TOP = TOP + 1 [Increment the TOP] Step 3: STACK[TOP] = ITEM [Insert the ITEM] Step 4: Return
  • 117. Stack Prof. Dr. K. Adisesha 117 POP Operation: The process of deleting one element or item from the stack is represented by an operation called as the POP operation. When elements are removed continuously from a stack, it shrinks at same end i.e., top:
  • 118. ALGORITHM: POP (STACK, TOP, ITEM) STACK is the array with N elements. TOP is the pointer to the top of the element of the array. ITEM to be DELETED. Step 1: if TOP = 0 then [Check Underflow] PRINT “ STACK is Empty or Underflow” Exit [End if] Step 2: ITEM = STACK[TOP] [copy the TOP Element] Step 3: TOP = TOP - 1 [Decrement the TOP] Step 4: Return Stack Prof. Dr. K. Adisesha 118 POP Operation: The process of deleting one element or item from the stack is represented by an operation called as the POP operation.
  • 119. Stack Prof. Dr. K. Adisesha 119 PEEK Operation: The process of returning the top item from the stack but does not remove it called as the PEEK operation. ALGORITHM: PEEK (STACK, TOP) STACK is the array with N elements. TOP is the pointer to the top of the element of the array. Step 1: if TOP = NULL then [Check Underflow] PRINT “ STACK is Empty or Underflow” Exit [End if] Step 2: Return (STACK[TOP] [Return the top element of the stack] Step 3:Exit
  • 120. Stack Prof. Dr. K. Adisesha 120 Program to demonstrate push and pop operation in stack in data structure in C #include <stdio.h> #include <stdlib.h> #define SIZE 4 int top = -1, A[SIZE]; void push(); void pop(); void show(); int main() { int choice; while (1) { printf("nPerform operations on the stack:"); printf("n1.Push n 2.Pop n 3.Shown4.End"); printf("nnEnter the choice: "); scanf("%d", &choice); switch (choice) { case 1: push(); break; case 2: pop(); break; case 3: show(); break; case 4: exit(0); default: printf("nInvalid choice!!"); } } }
  • 121. Stack Prof. Dr. K. Adisesha 121 Program to demonstrate push and pop operation in stack in data structure in C void push() { int x; if (top == SIZE - 1) { printf("nOverflow!!"); } else { printf("nEnter the element to the stack: "); scanf("%d", &x); top = top + 1; A[top] = x; } } void pop() { if (top == -1) { printf("nUnderflow!!"); } else { printf("nPopped element: %d", A[top]); top = top - 1; } } void show() { if (top == -1) { printf("nUnderflow!!"); } else { printf("nElements present in the stack: n"); for (int i = top; i >= 0; --i) printf("%dn", A[i]); } }
  • 122. Stack Prof. Dr. K. Adisesha 122 Application of Stacks:  It is used to reverse a word. You push a given word to stack – letter by letter and then pop letter from the stack.  “Undo” mechanism in text editor.  Conversion of infix expression into prefix and postfix.  Evaluation of Arithmetic Expressions  Delimiter Checking  Processing Function Calls  To solve tower of Hanoi.  To sort elements using Quick sort  Runtime memory management.
  • 123. An expression is a combination of operands and operators that after evaluation results in a single value.  Operand consists of constants and variables.  Operators consists of {, +, -, *, /, ), ] etc.  Expression can be  Infix Expression: If an operator is in between two operands, it is called infix expression.  Example: a + b, where a and b are operands and + is an operator.  Postfix Expression: If an operator follows the two operands, it is called postfix expression.  Example: ab +  Prefix Expression: an operator precedes the two operands, it is called prefix expression.  Example: +ab Stack Prof. Dr. K. Adisesha 123 Arithmetic Expression:
  • 124. Stack Prof. Dr. K. Adisesha 124 Arithmetic Expression: Converting an infix expression into a postfix expression. A+B/C+D*(E-F)^G
  • 125. Stack Prof. Dr. K. Adisesha 125 Arithmetic Expression:
  • 126. Stack Prof. Dr. K. Adisesha 126 Arithmetic Expression: Evaluating Postfix expression:  let us consider the following infix expression: 2 * (4+3) - 5.  Its equivalent postfix expression is: 2 4 3 + * 5.  The following step illustrates how this postfix expression is evaluated. Value=9
  • 127. Stack Prof. Dr. K. Adisesha 127 Delimiter Checking: The common application of Stack is delimiter checking, i.e., parsing that involves analyzing a source program syntactically.  To perform a delimiter checking, the compiler makes use of a stack.  It is also called parenthesis checking. Valid Delimiter Invalid Delimiter While ( i > 0) While ( i > /* Data Structure */ /* Data Structure { ( a + b) - c } { ( a + b) - c
  • 128. Stack Prof. Dr. K. Adisesha 128 Processing Function Calls: A call stack is a data structure used by computer programs to keep track of function calls.  When a Recursive function is called, a new frame is added to the call stack. function factorial(n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } }
  • 129. Queue Prof. Dr. K. Adisesha 129 Queue: A queue is an ordered collection of items where an item is inserted at one end called the “rear” and an existing item is removed at the other end, called the “front”.  Queue is also called as FIFO list i.e. First-In First-Out.  In the queue only two operations are allowed enqueue and dequeue.  Enqueue means to insert an item into back of the queue.  Dequeue means removing the front item.The people standing in a railway reservation row are an example of queue.
  • 130. Queue Prof. Dr. K. Adisesha 130 Queue: A queue is an ordered collection of items where an item is inserted at one end called the “rear” and an existing item is removed at the other end, called the “front”.
  • 131. Queue Prof. Dr. K. Adisesha 131 Memory Representation of Queue: The queue can be implemented into two ways:  Using arrays (Static implementation)  Using pointer (Dynamic
  • 132. Queue Prof. Dr. K. Adisesha 132 Memory Representation of Queue: Memory Representation of a queue using array:  Queue is represented in memory using linear array.  Let QUEUE is a array, two pointer variables called FRONT and REAR are maintained.  The pointer variable FRONT contains the location of the element to be removed or deleted.  The pointer variable REAR contains location of the last element inserted.  The condition FRONT = NULL indicates that queue is empty.  The condition REAR = N-1 indicates that queue is full.
  • 133. Queue Prof. Dr. K. Adisesha 133 Types of Queues : Queue can be of four types:  Simple Queue  Circular Queue  Priority Queue  De-queue ( Double Ended Queue)
  • 134. Queue Prof. Dr. K. Adisesha 134 Types of Queues : Simple Queue: Simple Queue is a linear data structure that follows the First-In-First- Out (FIFO) principle, where elements are added to the rear (back) and removed from the front (head).  When a new element is added, all elements added before the new element must be deleted in order to remove the new element.  Ordered collection of comparable data kinds.  Queue structure is FIFO (First in, First Out).
  • 135. Queue Prof. Dr. K. Adisesha 135 Types of Queues : Circular Queue: A circular queue is a special case of a simple queue in which the last member is linked to the first, forming a circle-like structure.  The last node is connected to the first node.  Also known as a Ring Buffer, the nodes are connected end to end.  Insertion takes place at the front of the queue, and deletion at the end of the queue.
  • 136. Queue Prof. Dr. K. Adisesha 136 Types of Queues : Priority Queue: In a priority queue, the nodes will have some predefined priority in the priority queue. The node with the higiest priority will be the first to be removed from the queue. Insertion takes place in the order of arrival of the nodes.  Some of the applications of priority queue:  Dijkstra’s shortest path algorithm  Prim’s algorithm  Data compression techniques like Huffman code
  • 137. Queue Prof. Dr. K. Adisesha 137 Types of Queues : Dequeue Queue:  Dequeue: It is a queue in which insertion and deletion takes place at the both ends.
  • 138. Queue Prof. Dr. K. Adisesha 138 Operation on Queues : The various operation performed on Queue are : Operation Description enqueue() Process of adding or storing an element to the end of the queue dequeue() Process of removing or accessing an element from the front of the queue peek() Used to get the element at the front of the queue without removing it initialize() Creates an empty queue isfull() Checks if the queue is full isempty() Check if the queue is empty
  • 139. Queue Prof. Dr. K. Adisesha 139 Queue Insertion Operation (ENQUEUE): ALGORITHM: ENQUEUE (QUEUE, REAR, FRONT, ITEM) QUEUE is the array with N elements. FRONT is the pointer that contains the location of the element to be deleted and REAR contains the location of the inserted element. ITEM is the element to be inserted. Step 1: if REAR = N-1 then [Check Overflow] Front Rear PRINT “QUEUE is Full or Overflow” Exit [End if] Step 2: if FRONT = NULL then [Check Whether Queue is empty] FRONT = -1 REAR = -1 else REAR = REAR + 1 [Increment REAR Pointer] Step 3: QUEUE[REAR] = ITEM [Copy ITEM to REAR position] Step 4: Return
  • 140. Queue Prof. Dr. K. Adisesha 140 Queue Deletion Operation (DEQUEUE):  ALGORITHM: DEQUEUE (QUEUE, REAR, FRONT, ITEM) QUEUE is the array with N elements. FRONT is the pointer that contains the location of the element to be deleted and REAR contains the location of the inserted element. ITEM is the element to be inserted.  Step 1: if FRONT = NULL then [Check Whether Queue is empty] Front Rear  PRINT “QUEUE is Empty or Underflow”  Exit  [End if]  Step 2: ITEM = QUEUE[FRONT]  Step 3: if FRONT = REAR then [if QUEUE has only one element]  FRONT = NULL  REAR = NULL  else  FRONT = FRONT + 1 [Increment FRONT pointer]  Step 4: Return
  • 141. Queue Prof. Dr. K. Adisesha 141 Application of Queue:  Operating systems: Operating systems often use queues to manage processes and resources. For example, a process scheduler might use a queue to manage the order in which processes are executed.  Task Scheduling: Queues can be used to schedule tasks based on priority or the order in which they were received.  Resource Allocation: Queues can be used to manage and allocate resources, such as printers or CPU processing time.  Event Handling: Queues can be used to handle events in event-driven systems, such as GUI applications or simulation systems.  Printer queues: In printing systems, queues are used to manage the order in which print jobs are processed. Jobs are added to the queue as they are submitted, and the printer processes them in the order they were received.
  • 142. Unit- 5 Prof. Dr. K. Adisesha 142 Non-Linear Data structures: Non-linear data structures in C the data is stored in multiple levels. The implementation of non-linear data structures is more complex than linear data structures  The different non-linear data structures are  Trees  Graphs.
  • 143. Non-Linear Data structures Prof. Dr. K. Adisesha 143 Non-Linear Data structures: A Non-Linear Data structures is a data structure in which data item is connected to several other data items:  The data items in non-linear data structure represent hierarchical relationship.  Each data item is called node.  The different non-linear data structures are  Trees  Graphs.
  • 144. Non-Linear Data structures Prof. Dr. K. Adisesha 144 Tree as data structure : A tree is a data structure consisting of nodes organized as a hierarchy:  Tree is a hierarchical data structure which stores the information naturally in the form of hierarchy style.  It is a non-linear data structure compared to arrays, linked lists, stack and queue.  It represents the nodes connected by edges.
  • 145. Non-Linear Data structures Prof. Dr. K. Adisesha 145 Terminology of a Tree:
  • 146. Non-Linear Data structures Prof. Dr. K. Adisesha 146 Tree as Data structure : Different Types of Trees in Data Structure:  Binary Tree  Ternary Tree  N-ary Tree  AVL Tree  Red-Black Tree  Binary Search-Tree  B- Tree
  • 147. Non-Linear Data structures Prof. Dr. K. Adisesha 147 Different Types of Trees in Data Structure:  Binary Tree : A Binary Tree is composed of nodes, where each node has at most two children, referred to as the left and right subtrees.  Ternary Tree : A Ternary Tree is a tree data structure in which each node has at most three child nodes, usually distinguished as “left”, “mid” and “right”.  N-ary Tree: An N-ary Tree is a generalisation of binary trees where each node can have up to N children, providing a more flexible and scalable hierarchical structure.  AVL Tree: AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one.  Red-Black Tree: A Red-Black Tree is a self-balancing binary search tree with the key innovation of assigning colours (red or black) to its nodes.
  • 148. Non-Linear Data structures Prof. Dr. K. Adisesha 148 Binary Tree: A binary tree is an ordered tree in which each internal node can have maximum of two child nodes connected to it:  A binary tree consists of:  A node ( called the root node)  Left and right sub trees.  A Complete binary tree is a binary tree in which each leaf is at the same distance from the root i.e. all the nodes have maximum two subtrees. Binary tree using array represents a node which is numbered sequentially level by level from left to right. Even empty nodes are numbered.
  • 149. Non-Linear Data structures Prof. Dr. K. Adisesha 149 Binary Search tree: In a Binary search tree, the value of left node must be smaller than the parent node, and the value of right node must be greater than the parent node.  A binary search tree follows some order to arrange the elements.  we can observe that the root node is 40, and all the nodes of the left subtree are smaller than the root node, and all the nodes of the right subtree are greater than the root node.  Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50  Steps - Insert 45 as Root.
  • 150. Non-Linear Data structures Prof. Dr. K. Adisesha 150 Full Binary Tree vs. Complete Binary Tree: A full binary tree can be defined as a binary tree in which all the nodes have 0 or two children.  In other words, the full binary tree can be defined as a binary tree in which all the nodes have two children except the leaf nodes.  A binary tree is said to be a complete binary tree when all the levels are completely filled except the last level, which is filled from the left. Full Binary Tree Complete Binary Tree
  • 151. Non-Linear Data structures Prof. Dr. K. Adisesha 151 Tree traversal: The term 'tree traversal' means traversing or visiting each node of a tree.  A Tree Data Structure can be traversed in following ways:  Depth First Search or DFS  Inorder Traversal  Preorder Traversal  Postorder Traversal  Breadth First Search or BFS  Boundary Traversal  Diagonal Traversal
  • 152. Non-Linear Data structures Prof. Dr. K. Adisesha 152 Depth First Search or DFS DFS, Depth First Search, is an edge-based technique.  It uses the Stack data structure and performs two stages, first visited vertices are pushed into the stack, and second if there are no vertices then visited vertices are popped.  Depth First Search or DFS  Inorder Traversal  Preorder Traversal  Postorder Traversal
  • 153. Non-Linear Data structures Prof. Dr. K. Adisesha 153 Depth First Search or DFS Inorder Traversal: This technique follows the 'left root right' policy. It means that first left subtree is visited after that root node is traversed, and finally, the right subtree is traversed. Algorithm: Until all nodes of the tree are not visited Step 1 - Traverse the left subtree recursively. Step 2 - Visit the root node. Step 3 - Traverse the right subtree recursively.
  • 154. Non-Linear Data structures Prof. Dr. K. Adisesha 154 Depth First Search or DFS Preorder Traversal: This technique follows the 'root left right' policy. It means that, first root node is visited after that the left subtree is traversed recursively, and finally, right subtree is recursively traversed. Algorithm: Until all nodes of the tree are not visited Step 1 - Visit the root node Step 2 - Traverse the left subtree recursively. Step 3 - Traverse the right subtree recursively.
  • 155. Non-Linear Data structures Prof. Dr. K. Adisesha 155 Depth First Search or DFS : Postorder Traversal: This technique follows the 'left-right root' policy. It means that the first left subtree of the root node is traversed, after that recursively traverses the right subtree, and finally, the root node is traversed. Algorithm: Until all nodes of the tree are not visited Step 1 - Traverse the left subtree recursively. Step 2 - Traverse the right subtree recursively. Step 3 - Visit the root node.
  • 156. Non-Linear Data structures Prof. Dr. K. Adisesha 156 Depth First Search or DFS : Construct Tree from given Inorder and Preorder traversals. Let us consider the below traversals:  Inorder sequence: D B E A F C  Preorder sequence: A B D E C F In a Preorder sequence, the leftmost element is the root of the tree. So we know ‘A’ is the root for given sequences. By searching ‘A’ in the Inorder sequence, we can find out all elements on the left side of ‘A’ is in the left subtree and elements on right in the right subtree. So we know the below structure now.
  • 157. Non-Linear Data structures Prof. Dr. K. Adisesha 157 Depth First Search or DFS: Construct Tree from given Inorder and Preorder traversals. Algorithm: buildTree()  Pick an element from Preorder. Increment a Preorder Index Variable to pick the next element in the next recursive call.  Create a new tree node tNode with the data as the picked element.  Find the picked element’s index in Inorder. Let the index be inIndex.  Call buildTree for elements before inIndex and make the built tree as a left subtree of tNode.  Call buildTree for elements after inIndex and make the built tree as a right subtree of tNode.  return tNode.
  • 158. Non-Linear Data structures Prof. Dr. K. Adisesha 158 Breadth First Search or BFS : BFS, Breadth-First Search, is a vertex-based technique for finding the shortest path in the graph.  It uses a Queue data structure that follows first in first out.  Breadth First Search or BFS  Boundary Traversal  Diagonal Traversal
  • 159. Non-Linear Data structures Prof. Dr. K. Adisesha 159 Applications of tree data structure Trees find applications in various fields, including.  Storing hierarchical data in File System  In chess game to store defense moves of player.  In server like DNS (Domain Name Server)  Web Search Engines  Computer Graphics.  To evaluate an expression  GPS Navigation systems  Artificial Intelligence
  • 160. Non-Linear Data structures Prof. Dr. K. Adisesha 160 Graph: Graph is a mathematical non-linear data structure capable of representing many kind of physical structures:  A graph is a set of vertices and edges which connect them.  A graph is a collection of nodes called vertices and the connection between them called edges.  Definition: A graph G(V,E) is a set of vertices V and a set of edges E.
  • 161. Non-Linear Data structures Prof. Dr. K. Adisesha 161 Graph: Graph is a mathematical non-linear data structure capable of representing many kind of physical structures:  An edge connects a pair of vertices and many have weight such as length, cost and another measuring instrument for according the graph.  Vertices on the graph are shown as point or circles and edges are drawn as arcs or line segment
  • 162. Non-Linear Data structures Prof. Dr. K. Adisesha 162 Graph: Types of Graphs:  Directed graph  Undirected graph  Simple graph  Weighted graph  Connected graph  Non-connected graph
  • 163. Non-Linear Data structures Prof. Dr. K. Adisesha 163 Graph Representation: There are two techniques to represent a graph:  Adjacency Matrix: In the adjacency matrix, each row and column define a vertex. It is a 2D array of V x V vertices.  Adjacency List: The index of the array defines a vertex, and every component in its linked list describes the other vertices that form an edge with the vertex. Adjacency Matrix Adjacency List
  • 164. Non-Linear Data structures Prof. Dr. K. Adisesha 164 Applications of Graph Data Structure: In Computer science graphs are used to represent the flow of computation.  Graphs are used to represent networks of communication.  Graph theory is also used in network security.  In Google Maps, is used to find shortest path in road or a network.  The World Wide Web is an example of a directed graph.  Facebook uses undirected graphs to identify a user and the user’s friends.  In Electrical Engineering, graph theory is used in designing of circuit connections.  graph data structures define and compute the transport system.
  • 165. Data structures Prof. Dr. K. Adisesha 165 Thank you:
  翻译: