0% found this document useful (0 votes)
2 views

Vidhya Institute Data Structure

Uploaded by

namarahul545
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Vidhya Institute Data Structure

Uploaded by

namarahul545
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 217

Ideal ‘Data Structure’

DATA STRUCTURE
Data is simply values or sets of values that is utilized in calculation or manipulation. When we process this
data then it becomes information. Data can be distinguished in different data types like integer, floating or character
type. A student’s name, age, class, marks are the examples of data. When these data can be collected and organized,
in some way, it is called record. For example, 18 is a data, because we don’t know its significance, while if we say
“Age of pearl is 18”. Now this becomes information. This statement has some significance. Also, if we store it in
computer as a ser <Name, age> then it is record e.g. <pearl, 18>, <John, 24> etc.
Data structure is representation of the logical relationship existing between individual elements of data. In
others words, a data structure is a way of organizing all data items that considers not only the elements stored but
also their relationship to each other.

The study of data structure includes the following four things.


1. Organization of data
2. Accessing methods
3. Degree of associatively
4. Processing alternative for information

To develop a program of an Algorithm, we should select an appropriate data structure.

This selection of data structure stresses on the following two things.


1. The data structure must be rich enough to reflect the relationship between the data.
2. The data structure should be simple so that data can be processed effectively

CLASSIFICATION OF DATA STRUCTURE


Data structures are normally divided into two broad categories.
1. Primitive data structures
2. Non- primitive data structures. Data
Structure

Primitive data Non primitive data


structure structure

Integ Flo Charac Point


er at ter er Arr List Fil
ay s es

Liner list Non – linear


list

Sta Que Tre Grap


ck ue e h
Classification of data Structure

1. Primitive Data Structure


These are basic structure and are directly operated upon by the machine in structions. Primitive Data
structure, always concerns with primitive data types. Primitive data types are also known ad inbuilt data types,
therefore primitive data structure are also called inbuilt or primary data structures.

2. Non – Primitive Data Structure


These are derived from the primitive data structure. Like primitive data structure, non – primitive data
structure concerns with non-primitive data types or user defined or secondary data types, hence non-primitive
data types are also called secondary or user defined data structures. The non-primitive data structure emphasize on
structuring of a group of homogeneous (same type) or heterogenous (different type) data items.

Basically data structures are classified into two categories:


i. Linear
ii. Non linear

 Vidhya Institute of Information Technology 


1
Ideal ‘Data Structure’

A data structure is said to be linear if its elements form linear sequence. Example of linear data structure
are Arrays, Stacks, Queues and linear Linked lists.
A data structure is said to be non – linear if its elements does not form linear sequence. Example of non –
linear data structure are Trees and Graphs.

There are two ways to represent linear information in memory.


(a) By continuous memory location.
(b) By pointer and links.

The possible operations on data structures are Traversal, Insertion, Deletion, Searching, Sorting and Merging.

 Traversing
Traversing means accessing each record exactly once, so that each record may be processed.
 Insertion
Adding a new data into the list any where at the specified location is called insertion.
 Deletion
Removing the existing data from the list is called deletion.
 Searching
It is a process of finding and element and its location in a collection of elements.
 Sorting
Sorting can be defined as rearranging the elements into a desired sequence either in
increasing or decreasing order.
 Merging:
Combining two different records into a single one.

ALGORITHMS
An algorithm is a step by step procedure to solve a particular problem. It means, it is a set of instructions
written to carry out certain tasks. It creates the logic of program. An algorithm is thus a sequence of instructions
that transform some input data into some output in a finite number of steps.
An algorithm is said to be correct, if for every input instance, it halts with the correct output. We say that a
correct algorithm solves to given computational problem. An incorrect algorithm might not halt at some input
instances.
Rules for writing an algorithm
There are following certain rules for writing an algorithm.
Rule 1. Begin: An algorithm should begin with ‘begin’ statement.
Rule 2. Variable Names: Variable names should be in capital letters.
For example, A, B, SUM or Sum
Rule 3. Assignment Statement: Assignment of values to variable should be in following manners:
Set A = 10 or Set A:10
Rule 4. Input Statement: Data may be print using following statement:
Read: A, B
Rule 5. Output Statement: Data may be print using following statement:
Write: A or Print: A
Rule 6. Declaration of variable: Variable should be declared using following statement:
Declare: A, B, SUM
Rule 7. Comments: Each step may contain a comment in bracket which indicates the main purpose of
the step. The comment will usually appear at the beginning or the end of step.
Rule 8. End or Exit Statement: The algorithm is completed when the statement ‘Exit’ or ‘End’ is
encountered.

Example 1.1 Algorithm for Sum of two integer variables


Step1. Begin
Step2. Declare: A, B, SUM
Step3. Read: A, B
Step4. Set SUM = A+B
Step5. Write: SUM
Step6. End.

 Vidhya Institute of Information Technology 


2
Ideal ‘Data Structure’

Performance Analysis and Measurement of an Algorithm


The efficiency of an algorithm depends on following two major criteria; first one is the space and second
is run time of that algorithm.
Analysis of algorithm or performance analysis refers to the task of determining how much computing time and
storage space an algorithm requires.

COMPLEXITY
The complexity of an algorithm M is the function f(x), which gives the running time and /or storage space
requirement of the algorithm in terms of the size ‘n’ of input data.
Mainly there are two types of complexity.
1. Space complexity
2. Time complexity

Space Complexity
The space complexity of an algorithm is the amount of computer’s memory it needs to run and compute
results. The space needed by algorithms is the sum of the following components
1. A fixed part that is independent of the characteristics (e.g. no. and size) of the Inputs and outputs. This
part includes the space needed by
 Instruction space
 Space for simple variables and fixed size components variables
 Space for constants
2. A variable part that consist of the space needed by
 Component variable whose size is dependent on the particular problem being solved.
 Referenced variable (this depends on instance characteristics)
 The recursion stack space.

Therefore the space complexity S(p) for any algorithm may be written as
S(p) = C + Sp(n)

Where C = Constance
n = instance characteristics

Example 1.2: Function to compute the sum of elements of an array having N elements.
1. Sum (ARR, N)
2. {
3. S:=0;
4. for I = 0 to N – 1 by 1
5. set S: = S + ARR[I]
6. return S;
7. }

 Vidhya Institute of Information Technology 


3
Ideal ‘Data Structure’

Here the problem instance are characterized by ‘N’ the number of elements to be summed
 The space needed by n is 1 Word
 The space needed by ARR is at least N Word
(Space ARR must be large enough to hold N elements)
 The space needed by I 1 Word
 The space needed by S 1 Word
Therefore total space needed by algorithm is (n+3).

Time Complexity
Time complexity of an algorithm is the amount of time that computer needs to run and compute the
result. The time taken by an algorithm is the sum of the compile time and the run or execution time. The
compile time dose not depend on the instance characteristics.
The time complexity of an algorithm is given by the number of steps taken by the algorithm to
compile the function it is designed for. The number of steps that are assigned to any program statement
depends on the kind of statement for example,
 Comments counts as zero steps.
 Assignment statement which does not involve any cells to other algorithm is counted as one step.
 In step iterative statement such as for, while, repeat- until etc. we consider the step counts only for the
control part of the statement.
Example 1.3: When the statement to increment count are introduced in above example the function becomes:

1. Sum (ARR, N)
2. {
3. S:=0
4. count:=count +1; //count is global initially zero
5. for I = 0 to N – 1 by 1
{
count := count +1; // for “for loop”
6. s:=s + ARR[1];
7. count := count +1; // for “Assignment”
}
8. count := count +1; // for “last time of for loop”
9. count := count +1; // for “return”
10. return S;
11. }

We are only interested in determining the changes in the value of count. For any initial value of count above
algorithm compute the final value for count.
In For loop value of count will increase by a total of 2N. If count is zero initially, then it will be 2N+3 on
termination. So each invocation of above algorithm executes total of 2N+3 step.

Therefore the time complexity of above function is 2N +3.


Major criteria for complexity of any algorithm is comparison of keys and moved of data, means number of
times the keys is compared and data is moved. Suppose space is fixed for one algorithm then only run time will be
considered for obtaining the complexity of algorithm. We take 3 cases for complexity of an algorithms-
1. Best case
2. Worst case
3. Average case

1. Best case
Generally most of the algorithm be have sometimes in best case. Best case means it should take shortest
time to execute the algorithm with the last amount of work. For example, for a searching algorithm he best case
would be if the element we are searching for is found in the first time. As a result this algorithm would need only
one composition irrespective how large is the input.

 Vidhya Institute of Information Technology 


4
Ideal ‘Data Structure’

2. Worst case
Generally we see the complexity of algorithm in it’s worst case behavior. When an algorithm takes most
time, it represents the worst case. For example, in liner search, when we find the element at the end or when
searching fails, then it behaves as worst case.

3. Average case
Analyzing the average case of behavior of algorithm is little bit complex than best case and worst case.
Average case of algorithm should be the average number of steps.

Asymptotic Notations
Asymptotic Notations are used to describe the time complexity in numerical form. This notation is called
“ASYMPTOTIC” because it deals with the behavior of functions in the limit, that is for sufficiently, large value of
its parameter.
Various asymptotic notations are
1. Big oh(0) notation
2. Omega (Ω) notation
3. Theta(θ) notation
4. Little 0 notation
5. Little omega notation

Big oh(0) notation


Big oh(0) is the method of expressing the upper bound of an algorithm’s running time. It is measure of the
longest amount of time it could possibly take for the algorithm to complete.
More formally, for non negative functions, f(n)and g(n), if there exists an integer n 0 and a constant C > 0
such that for a integer n > n0, f(n) ≤ c g(n) then. f(n) is Big 0 of g(n). This is denoted as

f(n) = 0 (g(n))

Cn(g(n)

f(n)

n
f(n)
Example 1.4: Let us say that f(n) = 2n +8 and g(n) = (n)2 we have to find an integer n0 and a constant C such that
for integer n > n0 , fn ≤ cn2
Suppose we choose C = 1 then

f(n) ≤ cn2
2n + 8 ≤ n2
0 ≤ n2 -2n – 8
0 ≤ (n+2) (n-4)

Since ( n +2 ) > 0 for all values of n ≥ 0, we conclude that (n-4) ≥ 0


i.e. n≥4
therefore we can say that n0 = 4.
So, we have that for C = 1 and n0 = 4 ; f(n) ≤ cn2 for all integers n ≥ n0. Hence f(n) = 0(n2).
It could then be said that f(n) runs in 0(n2) times:
“f – of – n runs in Big – 0 of n – squared times.”

 Vidhya Institute of Information Technology 


5
Ideal ‘Data Structure’

Omega (Ω) Notation


This is the method of expressing the lower bound of an algorithms running time. It is a measure
of the lowest amount of time it could possibly take for the algorithm to complete.
For non – negative functions, f(n) and g(n), if there exist an integer n0 and a constant c > 0 such that all integers n
> n0, f(n) ≥ cg(n). then f(n) is omega of g(n). This is denoted as

f(x) = Ω (g(n)).

f(n)

C(g)(n)

n
n0

Example 1.5: Consider that f(n) = 5n2 – 64n + 256 and g(n) = n2 we have to find an integer n0 and a constant
c such that for all integer n > n0; f(n) ≥ cn2

Suppose we choose c= 1 then


f(n) ≥ cn2 => 5n2 – 64n +256 ≥ n2
=> 4n2 – 64n + 256 ≥ 0
=> 4(n-8)2 ≥ 0
Since (n - 8)2 > 0 for all values of n ≥ 0 we conclude
that n0 = 0.
So we have that for c = 0 and n0 = 0, f(n) ≥ n0. Hence
f(n) = Ω(n2)

Theta (θ) Notation


For non – negative functions, f(n) and g(n), f(n) is theta of g(n) if and only if f(n) = 0 (g(n)) and f(n) = Ω(g(n)). This
is denoted as “f(n) = θ(g(n))”.
C2(g(n))

f(n)

C1(g(n))

n
n0
In other words, for n ≥ n0, the function f(n) belongs n, lies between c1 (g(n)) and c2(g(n)) i.e. lower bound and
upper bound of function. We say that g(n) is n asymptotically tight bound for f(n).
This is basically saying that the function, f(n) is bounded both from the top and bottom by the same
function g(n).

Little – 0 Notation
For non – negative functions, f(n) and g(n), f(n) is little 0 of g(n) if and only if f(n) = 0 (g(n)), but
f(n) ≠ (g(n)). This is denoted as
n) = 0 (g(n))
This represents a loose bounding version of Big 0. g(n) bounds form the TOP but it does not bound the
bottom.

 Vidhya Institute of Information Technology 


6
Ideal ‘Data Structure’

Little Omega Notation


For non negative functions, f(n) and g(n) is little omega of g(n) if and only if f(n) = ω(g(n)), but f(n) ≠ θ (g(n)).
This is denoted as
f(n) =ω(g(n))
g(n) is a loose lower boundary of the function f(n); it bounds from the bottom, but not from the top.

1.7 Big “OH” Notation


Big oh is a characterization scheme that is used to measure the performance of any algorithm.
Performance of any algorithm depends upon the volume of input data. It is proportional to the input data, 0
notation is used to define the order of growth for any algorithm.
The algorithm complexity can be determined ignoring the implementation dependent factors. This is done
by eliminating constant factors in the analysis of the algorithms.
The function f(n) = 0[g(n)]

Categories of ‘Big oh’ Notation


O(1)means a computing time that is constant.
O(n) is called quadratic.
O(n2) is called cubic.
O(n3) is called exponential.
O(2n) is called logarithmic.
O(log n) is called logarithmic
If an algorithms takes time o(log n), it is faster for sufficiently large n, than if it had taken O(n).
Similarly, O(n log n) is better than O(n2) but not as good as O(n).

Example 1.6: Write an algorithm to swap the value of two variables.


Solution:
Step 1: Declare: A, B, TEMP
Step 2. Read: A, B
Step 3. Set TEMP = A
Step 4. Set A = B
Step 5. Set B = TEMP
Step 6. Write: A, B
Step 7. End

ARRAY
 A single variable which can hold multiple values of the same type.
 No. of values specified in subscript [square Bracket]
int [10] Integer Array

Subscript
 It is also called linear array or 1-D array.
 When multiple subscript is used is called multidimensional array.
 When 2 subscript is used is called 2-D array.
 Array is a “Contiguous Memory Allocation”.
Address of 1-D Array
Loc (LA (K)) = Base Address (LA) + W (k-1)

It is a formula by which we can find out the address of a given location K in Array.
Here
LA Linear array
Base (LA) Base Address of LA
W Word Length (Database size)
K Location of element

 Vidhya Institute of Information Technology 


7
Ideal ‘Data Structure’

2-D ARRAY
 Multiple Dimension can be Specified
 When 2 Dimension is used is called 2-D Array
 Two Subscript is used
 One is specify Rows .(i) int a [3][3]
Second Specify No. of Column. (j)
1. Row major form
2. Column major form

Address of element in 2-D Array of M x N

Formula 1:
For Column Major Order
Loc (A[i, j]) = Base (A) + W [M (i-1) + (j-1)]
Formula 2:
For Row Major Order
Loc (A [i, j]) = Base (A) + W [N (j-1) + (i-1)]

For Example:
MxN 25*4
Base (A) 200
W 4
Row Major A [12, 3] = ?
j=12, k=3

Loc (A[12, 3]) = 200+4 [4 (11) + (2)]


= 200 +4 [44+2]
= 200 + 4*46
Loc (A [12, 3]) = 384
 So by using above formulas, the address of a given location element can be easily find out
 Row or Column major type must be considered.

 Vidhya Institute of Information Technology 


8
Ideal ‘Data Structure’

MATRIX
2-D Array is also Called as matrix.
Algo
Matrix – Addition (mat a, mat b, mat c, r,c)
Here
mat a Matrix a
mat b Matrix b
mat c Addition of mat a & mat b
r No. of Rows.
c No. of Columns.

Step 1: Repeat step 2 for i=1, 2…………r


Step 2: Repeat step 3 for j=1, 2………...c
Step 3: Set mat c[i,j]:= mat a [i,j] + mat b [i,j]
End of loop j
End of loop i
Step 4: Exit

Note: - For Subtraction only step 3 will change by following.


Set mat c[i,j]:= mat a [i,j] – mat b [i,j]
Algo: - Matrix Transpose
Transpose of a matrix refers to A= Λ T
Means when Rows of A Converted to Column.
Column of A Converted to Rows.

Algo: -

T MATRIX (A, AT, Row, Col)

Step 1: Repeat Step 2


For i=1, 2…………row
Step 2: Repeat Step 3
For j=1, 2…………Col
Step 3: Set AT[i,j]: = A [j, i]
[(AT [row, col] : = A [col, row)]
End of loop j
End of loop i
Step 4: Exit

Now Finally AT Matrix Contain Transpose of A Matrix.

 Vidhya Institute of Information Technology 


9
Ideal ‘Data Structure’

SQUARE MATRIX
A Matrix where no of Rows & No. of Column are always equal.
A [r][c], Where r=c

Diagonal Matrix
A Diagonal Matrix is a matrix whose all diagonal elements are zero (0)
Matrix A is Diagonal
If A[i,j]=0 for all i ≠ j

Tridiagonal Matrix
A Tridiagonal Matrix is a matrix who all diagonal, lower Diagonal, upper
Diagonal element are not zero (0)
Matrix, A is Diagonal

Lower Triangular matrix

Upper Triangular Matrix

 Vidhya Institute of Information Technology 


10
Ideal ‘Data Structure’

SPARSE MATRIX
 A matrix is a sparse matrix if no. of elements are zero (0).
 A matrix which is not sparse is called Dense matrix.

DENSE MATRIX
 When any M X N Sparse Represent in the memory then it occupy M X N blocks.
 But No. of element are zero.
 So that is wasting of memory.
 For Example: - Diagonal, Lower Triangular, etc. are comes under the category of sparse
matrix.
 So representing the sparse matrix is so much wasting of memory.
 That’s why different-2 types of technique is used to represent the sparse matrix
(A). By Array.
(B). By Linked List.

(A) By Array
For Representing the sparse matrix using array 2-D Array is used with fixed format.
 No. of columns are always 3.
 No. of rows are : = No. of Non Zero elements of sparse matrix + 1
 First Row represent No of Rows, No of Columns and No of Non Zero Elements.
 Remain rows contains Row no, Columns No. and Non Zero Element value.
For Example:-
Consider Sparse Matrix

(B) By Linked List


 If any New Element or When any Zero replace by any new element in sparse matrix
 then matrix Representation can not be altered.
 Because the No. of Rows & No. of Column of the matrix can not be increased or
 Decreased at Run time it is a static memory allocation.
 So this can be done by linked list, because it is a Dynamic Memory Allocation.
 At Run time required memory can be allocated or Deallocated.
 So Sparse matrix is easily represented by Linked list.

Linked List Representation


 Three different types of nodes are used.
(a) One Head OR Node

Pointer to the Row’s Node.

No. of Data part = 3


No. of Rows
No. of Add part = 1
No. of Column
No. of Non Zero element

 Vidhya Institute of Information Technology 


11
Ideal ‘Data Structure’

(B) Row Node


Pointer to Next Column Node

No. of Data part= 1


Rows No. No. of Add part = 1

Pointer to next Rows

(C) Column Node

Pointer to Next Column Node


No. of Data part= 2
Columns No. No. of Add part = 1

Value

Pointer to Next Column Node

Column No.
No. of Data part= 2
No. of Data part = 1
Element Value

For Example:- Sparse Matrix Is..

Now as per Requirement with in this representation new Node [Element] can be inserted Or
Deleted.

 Vidhya Institute of Information Technology 


12
Ideal ‘Data Structure’

STACK
Different – different types of data structure we have, Stack is also one of the most important and most
useful data structure.
 Stack is a special data structure which is based on LIFO [Last In First Out] technique.
 Stack is a Linear Data Structure.
 When we insert number of balls with in a pipe which is closed from one side, that type of structure is
called as “Stack”.
 In case of stack, any type of operation or task will be done at one point. Means insertion & deletion will be
done at same location, generally we call this location as Top.
Concept of LIFO
LIFO refers to Last In First Out, means element which comes or inserted at last in structure, will be
moved out first from structure. That is LIFO.
 Suppose we insert red ball then blue ball and then green ball in a pipe.
 Now if we want to access or move out any ball from that pipe, then
Only green will be moved out first, than blue and then red.So the element which is inserted at the last in
structure is moved out first. That concept is LIFO and stack is based on this concept.
Stack Implementation
stack can be implemented in two ways:
1 static implementation
2 Dynamic implementation
Static Implementation
It uses array to create stack. Static implementation is the most widely used technique but it is not too
efficient with respect to memory utilization, because in static implementation the size of stack has to be declare
during the program design. now suppose if there are few elements to be stored in the stack, some allocated memory
will be wasted. on the other hand if there are a large number of element to be stored in the , then we cant change
the size of array and our purpose is not solved in both ways.
Dynamic Implementation
It is achieved using linked list that uses pointers to implement the stack. Dynamic implementation is the
most widely used technique and it is too efficient with respect to memory utilization, because in Dynamic
implementation the size of stack has to be declare during the execution. now suppose if there are few elements to
be stored in the dynamic stack, some allocated memory will not be wasted. on the other hand if there are a large
number of element to be stored in the, then we can change the size of linked list and we can release the memory.
our purpose is solved in both ways.

Various Operations on Stack


Different types of operation can be performed on Data Structure. Generally these are Insertion, Deletion or
Display etc.
Operation On Stack
1. PUSH
“Insertion of elements in Stack”.
When we insert element in stack, that operation is called as PUSH. It will be done at top location of the stack.
2. POP
“Deletion or removal of element from Stack”.
When any element is deleted or removed from stack, that operation is called as POP. It will also be done at top
location of stack.
3. PEEK/PEEP
“Only access elements from the stack without removing it from stack”.
When we want to know that which element is present or stored at top location or which one will be popped when
we pop. So only just access the element from stack from the top without removing it from structure. That is known
as PEEK operation.
4. DISPLAY
It is a process of showing all the elements of stack within LIFO fashion. Display does not remove
the element from Stack; it only shows all the element.
5. IS EMPTY
It is optional; it is basically used for internal processing. This operation identify whether the stack is empty or not.
6. IS FULL
It is also optional, it also works like isempty. It is used to identify whether the stack is full or not.

 Vidhya Institute of Information Technology 


13
Ideal ‘Data Structure’

Note
As we know that stack is based on LIFO fashion/ technique, means all operation (push / pop / peek) will be
done at same location that is top. So all above operations will be done at top location.
Diagrammatically Representation Of Stack Operation
Initially top will be -1, because, initially stack will empty and top can be 0, but in case of array 0(zero) is a valid
location of element that’s why we initialize top by 0.
 When we PUSH element in stack, then top increase by one.
 When we POP element from stack, then top decrease by one.
1. Push Operation Representation 4 10
Initial stack of 5 elements:
3 20
2 32
1 25
0 52
top = -1
Pushing of 10, 20, 30, 40, & 50 one by one.
PUSH PUSH PUSH PUSH PUSH
10 20 30 40 50

4 10 10 4 10 4 10 4 10 4 50 4top
10

top = top+1
40 3
top = top+1

top = top+1

top = top+1

top = top+1
3 20 20 3 20 3 20 3 40 3top
10
2 32 32 2 32 2 30 2top 30 2 30 2
1 25 25 1 20 1top 20 1 20 1 20 1
0 52 10 0top 10 0 10 0 10 0 10 0
top = -1

Pop Operation Representation


Initial stack
top  50 4
3 40
2 30
1 20
0 10
top = 4

Pop of element one by one from stack then


POP POP POP POP POP
50 40 30 20 10

50 104 50 4 50 4 50 4 50 4
40 3top 40 3 40 3 40 3
top = top-1

top = top-1

top = top-1

top = top-1

40 3
top = top-1

10
30 2 30 2top 30 2 30 2 30 2
20 1 20 1 20 1top 20 1 20 1
10 0 10 0 10 0 10 0top 10 0

Peek 40 30 20 10 (stack underflow)


[Here dot representing the deleted element]
Stack operation with ARRAY (CODING)

 Vidhya Institute of Information Technology 


14
Ideal ‘Data Structure’

PUSH COADING
void push(void)
{
if(top==MAX-1)
printf(“\n stack overflow ”);
else
{
top=top+1;
printf(“\n Enter the element ”);
scanf(“%d”,&a[top]);
}
}
Algorithm of push operation in the stack
let Stack is an array having MAX elements for implementing the stack.

Step 1 : start.
step 2 : [check for stack overflow ?]
if top=MAX-1 ,then :
(a) print “overflow”
step 3: set top=top+1 [increase top by 1]
step 4: [add num in stack] set stack[top]=num [read num on stack[top]]
[end of if structure]
step 5: stop.

POP CODING
void pop(void)
{
if(top==-1)
printf(“\n stack underflow ”);
else
{
printf(“\n poped element %d”,a[top]);
top=top-1;
}
}

Algorithm of pop operation in the stack


let Stack is an array having MAX elements for implementing the stack.
Step 1 : start.
step 2 : [check for stack overflow ?]
if top=-1 ,then :
(b) print “underflow”
otherwise
step 3: print “poped element ”a[top]
step 4: set top=top-1.
[end of if structure]

step 5: stop.

PEEK CODING
void peek(void)
{
if(top==-1)
printf(“\n stack underflow ”);
else
printf(“\n peeked element %d”,a[top]);
}

 Vidhya Institute of Information Technology 


15
Ideal ‘Data Structure’

Algorithm of pop operation in the stack


let Stack is an array having MAX elements for implementing the stack.
step 1 : start.
step 2 : [check for stack overflow ?]
if top=-1 ,then :
print “underflow”
otherwise
step 3: print “poped element ”a[top]
[end of if structure]
step 5: stop.

TRAVERSE OPERATION
void traverse(void)
{
if(top==-1)
printf(“\n underflow”);
else
{
for(i=top;i>=0;i--)
printf(“ %d”,a[i]);
}
}
Algorithm of traverse operation in the stack
let Stack is an array having MAX elements for implementing the stack.
Step 1 : start.
step 2 : [check for stack overflow ?]
if top=-1 ,then :
print “underflow”
otherwise
step 3 : repeat step 4 for i=top to 0 by step -1
step 4: print a[i]
[end of loop]
[end of if]
step 5: stop.

Display Operation Representation


It is the process of displaying all elements of stack from top to initial (0) location without
removing them.
Ques: Why it is not from initial to top location?
Because stack works on LIFO and top represents last element, that’s why it will come out first.
So we access these elements from top to zero,.

4 50  top 4 4
3 40 3 3
2 30 2 30  top 2 s
1 20 1 20 1
0 10 0 10 0
Display: -50 40 30 20 10 30 20 10 stack underflow

 Vidhya Institute of Information Technology 


16
Ideal ‘Data Structure’

Application / Use of Stack


Stack is a very powerful & useful structure to perform. So many different – different types of tasks to be
performed.

 In Calling Function
When any function calls another function then control again comes back to calling function. So at this time for
coming back, the address of this calling function stored by stack.

 In Passing The Parameter With In A Function


When we pass parameter to a function then these all parameters move to stack and when we pass to calling
function then these parameter again pop from stack and pass to their concern formal argument, at this time error
may occur either for few parameter of for extra parameter.

 Specifying The Scope of A Variable

 Function Recursion
During recursion, when function calls itself then passing values and intermediate values are maintained within Stack.
Recursion always maintain stack.

 In Parenthesis Checking
Parenthesis checker is a program which is used to find out that entered equation is properly parenthesized or not,
this program is implemented with the help of stack.
“Our system also check that the equation with the same type program.”
((3+2) *4 wrong
{(3+2}) *4 wrong
{(3+2}) *4] wrong
[{(3+2)} *4] right

Algorithm To Check The Correct Nesting Of Parentheses


Take a Boolean variable VALID which will be true if the expression is valid and false if the expression is invalid.
1: begin
2: initialize an empty stack and set VALID =true.
3: scan the expression from left to right and repeat 4 & 5 , until the end of expression is encountered.
4: if the symbol is left parenthesis, then : push it onto the stack.
5: if the symbol is a right parentheses , then:
if the stack is empty: then,
(a) set VALID= false
else
(b) pop an element from the stack.
(c) if popped parentheses is not the left parentheses, then:
(d) set VALID=false
[end of if]
6: if stack is not empty then: set VALID =false
7: if valid = false
print : ” not match ”
else
print “match”
[end of if ]
8: stop.

 Vidhya Institute of Information Technology 


17
Ideal ‘Data Structure’

Practical Implementation
#include<stdio.h>
#include<process.h>
#include<conio.h>
void main()
{
char s[100],stack[50],ch1,ch2;
int i,top=-1;
clrscr();
printf("\nEnter Expression for Paranthesis Checker : ");
gets(s);
for(i=0;s[i]!=NULL;i++)
{
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
stack[++top]=s[i];
else
{
if(top==-1)
{
printf("\nInvalid Expression");
getch();
exit(0);
}
else
{
if(s[i]==')' || s[i]=='}' || s[i]==']')
{
ch1=s[i];
ch2=stack[top--];
switch(ch2)
{
case '(': ch2=')'; break;
case '{': ch2='}'; break;
case '[': ch2=']'; break;
}
if(ch1!=ch2)
{
printf("\nInvalid Expression");
getch();
exit(0);
}
}
}
}
}
if(top==-1)
printf("\nCorrect Expression");
else
printf("\nInvalid Expression");
getch();
}

Expression evaluation
An Expression is made of operands. operators and delimiters. In most programming language , arithmetic expressions
are written as :
X=A*B-C-D/E.
this expression have five operands : A B C D E
PRECEDENCE OF OPERATORS IN C
PRIORITY OPERATOR
1. [],{},<>,()
2. ^
3. *,/,%
4. +,-
5. <,>,<=,>=
6. ==,!=
7. &&
8. ||

 Vidhya Institute of Information Technology 


18
Ideal ‘Data Structure’

TYPE OF NOTATION
INFIX in infix notation operators are placed in between the operands.
a+b (infix)

POSTFIX in postfix notation operators are placed after the operands.


a+b (infix)
ab+ (postfix)

PREEFIX in postfix notation operators are placed after the operands.


a+b (infix)
+ab (prefix)

Evaluation of Postfix
For evaluation of postfix expression, we maintain the stack. The stack should be used to store the
operations. For evaluation, the postfix expression is scanned from left to right. When an operand is found, it is
pushed onto the stack and when an operator is found, the last two operands are popped from the stack. Then
required operations is applied to them and their result is pushed onto the stack. Hear we have no need of
information of operator precedence.
Let us take an array postfix which has arithmetic expression in postfix from. The steps involved to
evaluate postfix expression eill be :-

Step 1- Scan the symbols of array postfix one by one from left to right.
Step 2- If symbol is opened, then push it to stack.
Step 3- If symbol is operator then pop last two elements of stack and evaluate it as
[top-1] operator [top]
Step 4- Do the same process unit scanning of postfix array not ends.
Step 5- Pop the element of stack which will be the value of evaluation of postfix arithmetic expression.

Let us take a postfix expression and evaluation it-


4, 5, 4, 2, ^, +, *, 2, 2, ^, 9, 3, /, *, -
Now, we will apply the procedure to the above postfix expression.
Step Symbol Stack
1 4 4
2 5 4, 5
3 4 4, 5, 4
4 2 4, 5, 4, 2
5 ^ 4, 5, 16
6 + 4, 21
7 * 84
8 2 84, 2
9 2 84, 2, 2
10 ^ 84, 4
11 9 84, 4, 9
12 3 84, 4, 9, 3
13 / 84, 4, 3
14 * 84, 12
15 - 72
So after evaluation of the postfix expression it’s value is 72 Let us take the same postfix expression in infix from
and evaluate it..

Algorithm To Evaluate A Postfix Notation

Following algorithm summarizes the procedure:


1. Begin
2. Initialize an empty stack
3. Repeat step 4 &5, until the end of expression is encountered.
4. If an operand is encountered, then push it onto.
5. If am operator is encountered, then

 Vidhya Institute of Information Technology 


19
Ideal ‘Data Structure’

a. Pop the two values from the stack.


b. Apply the operator to these values.
c. Push the result of step ‘b’ back onto the stack.
[ End of If structure]
[ End of step 3 loopp]
5. At the end of expression, result is contained at the top of the stack.
6. End.
Practical Implementation of Evaluation of Postfix Expression Logic
#include<stdio.h>
#include<conio.h>
void main()
{
char s[100],i,op;
int stack[50];
int top=-1,op1,op2,op3;
clrscr();
printf("\nEnter Any Postfix Expression : ");
gets(s);
for(i=0;s[i]!=NULL;i++)
{
if(s[i]>='0' && s[i]<='9')
stack[++top]=s[i]-48;
else
{
op=s[i];
op1=stack[top--];
op2=stack[top--];
switch(op)
{
case '+' : op3=op2+op1; break;
case '-' : op3=op2-op1; break;
case '*' : op3=op2*op1; break;
case '/' : op3=op2/op1; break;
}
stack[++top]=op3;
}
}
printf("\nOutput Of Expression Is : %d",op3);
getch();
}

Conversion From Infix To Postfix Notation


Before conversion the infix expression into postfix expression , we need to assume. Here we are scanning from
left to right and operators involve are only ‘^’ (expression), ‘+’, ‘-‘, ‘*’ and ‘/’. We will need to implement stack
for temporary placement of operators and information of operator will also be required. For getting the
information of end of arithmetic expression, addition of one unique symbol is needed at the end.
Let us take an array infix which has arithmetic expression in infix from and array postfix will contain the
arithmetic expression in postfix from. The steps involved to convert the infix expression into postfix
expression will be-

Step 1- Add the symbol ‘(‘into stack &’)’ at the end of array infix.
Step 2- Scan the symbols of array postfix one by one from left to right.
Step 3- If symbol is left parenthesis ‘(‘ then add it to stack.
Step 4- If symbol is operand then add it to array postdix.
Step 5-
(i) if symbol is operator then pop the operators which have same precedence or higher precedence
then operator which occurred.
(ii) Add the popped operator to array postfix.
(iii) Add the scanned symbol operator into stack.

 Vidhya Institute of Information Technology 


20
Ideal ‘Data Structure’

Step 6-
(i) If symbol is right parenthesis ‘)’ then pop all the operators from stack until left parenthesis ‘(‘ in
stack.
(ii) Remove the left parenthesis ‘(‘ in stack..
Step 7-
Do the same process until scanning of array infix not ends
Let us take an infix expression and convert it into postfix
A*(B+C^D)-E^F*(G/H)
Initially ‘(‘ will be added in stack and ‘)’ at the end of infix expression.
So now the infix expression will be-
A*(B+C^D)-E^F*(G/H)
Step Symbol in stack Operator Expression postfix
1. A ( A
2. * (* A
3. ( (*( A
4. B (*( AB
5. + (*(+ AB
6. C (*(+ ABC
7. ^ (*(+^ ABC
8. D (*(+^ ABCD
9. ) (* ABCD^+
10. - (- ABCD^+*
11. E (- ABCD^+*E
12. ^ (-^ ABCD^+*E
13 F (-^ ABCD^+*EF
14. * (-* ABCD^+*EF^
15. ( (-*( ABCD^+*EF^
16. G (-*( ABCD^+*EF^G
17. / (-*(/ ABCD^+*EF^G
18. H (-*(/ ABCD^+*EF^GH
19. ) (-* ABCD^+*EF^GH/
20. ) ABCD^+*EF^GH/*-
So now the postfix expression is-
A B C D ^ + * E F ^ G H / * -
We know that the result postfix expression is parentheses free and operators are in order of sequence of evaluation
with operands.

Algorithm To Convert An Infix Expression Into Postfix Notation


To convert an infix notation into postfix, we suppose ‘E’ as an expression written in infix notation. This
algorithm finds the equivalent postfix notation ‘P’ Postfix (E, P)
1. Begin
2. Initialize an empty stack of operators. Add ‘(‘ to stack and’)’ at the end of infix expression.
3. Scan E from left to right and represent step 4 to7 for each element of E.
4. If element is a left parentheses, then : push it onto the stack.
5. If element is an operand, then : add (or display) it to P
6. If element is an operator, then check.
(a) If stack is empty or operator has higher priority then the operator at the top of stack,
then:
(b) push the higher priority operator on to the stack.
else
(c) pop the top operator of stack and display or add it to P, and then repeat the comparison
of operator with the new top stack item,
7 If Element is a Right Parentheses then pop and display or add to P , stack element until a left
parentheses is encountered (Do not display or Add ) the Left Parentheses).
8 When the end of infix expression is reached , pop and display stack items, until the stack is
empty.
9 End
7. Reversal of string
we can reverse the string by pushing the element in to the stack
8. Stack is also used in DFS (Depth First Search) algorithm of graph structure.

 Vidhya Institute of Information Technology 


21
Ideal ‘Data Structure’

TOWER OF HANOI

#include<stdio.h>
#include<conio.h>
void tower(char , char ,char ,int );
void main()
{
int n;
clrscr();
printf("\n Enter the Number Of Plates ");
scanf("%d",&n);
tower('A','B','C',n);
getch();
}
void tower(char ch1, char ch2, char ch3, int n )
{
if(n==1)
printf("\n %c => %c",ch1,ch3);
else
{
tower(ch1,ch3,ch2,n-1);
tower(ch1,ch2,ch3,1);
tower(ch2,ch1,ch3,n-1);
}
}

 Vidhya Institute of Information Technology 


22
Ideal ‘Data Structure’

Practical Implementation Of Stack


#include<stdio.h>
#include<conio.h>
#include<stdlib.h> /* exit 0 function */
#define max 10
int a[max],top=-1;
void main()
{
int i, ch;
while(1)
{
clrscr();`
switch(ch)
{
case 1:
if(top= = n-1)
printf(“\n stack overflow”);
else
{
top++;
printf(“\n enter the element which you want to push:-”);
scanf(“%d”,&a[top]);
printf(“\n %d element pushed succesfully”t);
}
break;
case 2:
if (top = = -1)
printf(“\n stack underflow”);
else
{
printf(“\n %d element is going to pop”, a[top]);
top--;
}
break:
case 3:
if (top==-1)
printf(“\n stack underflow”);
else
printf(“\n peek element is %d”, a[top]);
break;
case 4:
if (top = =-1)
printf(“\n stack underflow”);
else
{
printf(“\n stack elements are :- ”);
for (i=top; i>=0; i--)
printf(“\n %d”,a[i]);
}
break;
case 5:
exit(0);
default:
printf(“\n in valid choice”);
printf(“\n try again based on given menu”);
} //closing of switch
getch();
// closing while loop
} // closing of main() function &program

 Vidhya Institute of Information Technology 


23
Ideal ‘Data Structure’

 It is a menu driven program. When we run this program, then a menu will be displayed in front of us
which provide us various options to perform operation of the stack selected by us.
 In this program maximum 10 elements can be pushed and if we want to increase this capacity, then
increase the value of n, which is defined as a Symbolic Constant along with header files with the
help of # define.
 This program will not close or stop until you press 6(exit) button.

QUEUE
In number of data structure, we have a Queue Data Structure also. Queue is also one of the most
important and useful data structure.
 Queue is a special data structure which is based in FIFO [FIRST IN FIRST OUT] technique.
 Stack is a linear data structure.
 When we insert number of balls with in a pipe which is open from both sides, that type of structure or
arrangement of element is known as queue.
 This queue data structure is exact similar to our queue just as queue of student for purchasing examination
form.
 Queue of passengers waiting for bus.
 In case of queue, any type of operation or task will be done at two different- different points, means
Insertion &Deletion will be done at two locations. These are f [Front] & r [Rear]
 Front location is used for deletion of element.
 Rear location is used for insertion of element.
Concept of FIFO
FIFO refers to First In First Out, means element which comes or inserted first in structure, then it will
move out or deleted first from structure [same as queue of persons] that is [FIFO].
 Suppose we insert red ball then blue ball and then green ball in the pipe which is open from both side.
 Now if we want to access or move out any ball from this pipe, then only red will move out first, then blue
and then green because queue is based on FIFO concept.
 So the element which is inserted first in the structure then it will be move out first from the structure, that
concept is FIFO and queue is based on FIFO concept.
Various Operations On Queue
If we implement any data structure then numbers of operations are needed to be performed on that
structure. So operations which can be performed on queue are specified below:
1 ENQUEUE 2 DEQUEUE
3 PEEK 4 DISPLAY
ENQUEUE
“Insertion of element in Queue”
When we insert element in queue, that operation is called as Enqueue. It is done at the rear location of
queue.

void enqueue(void) Step 1 : start.


{ Step 2: check if (rear=max-1) then,
if (rear==max-1) Print “ overflow”.
printf(“\n overflow”); Otherwise
else Step 3: set rear=rear+1.
{
Step 4: read element on a[rear].
rear++;
[end of if]
pritnf(“\n enter the element ”);
Step 5: stop
scanf(“%d”,&a[rear]);
}
}
DEQUEUE
“Deletion of element from Queue”
When we declare any element from queue that operation is Step 1: start.
called as dequeue. It is done at the front location of Queue. Step 2: check if (front>rear) then,
void dequeue(void) Print “underflow”
{ Otherwise
if(front>rear) Step 3: print “dequeued element”a[front]
printf(“\n underflow”); Step 4: set front:=front +1.
[end of if]
Step 5: Stop.

 Vidhya Institute of Information Technology 


24
Ideal ‘Data Structure’

else
{
printf(“\n dequeued element %d”,a[front]);
Front++;
}
}

PEEK/PEEP
“Only accessing the element from the queue without removing it from Queue”
When we want to know that which element is present or stored at front location or which
element wii be removed when we do so, that’s why just for accessing the element from queue from the front
location without removing it from queue. This is known as PEEP operation.
void peek(void)
{ Step 1: start.
If(front>rear) Step 2: check if (front>rear) then,
printf(“\n underflow”); Print “underflow”
Else Otherwise
printf(“\n peeked element %d”,a[front]); Step 3: print “peeked element” a[front]
} [end of if]
Step 4: Stop.
Display
It is the process of showing all the element of queue within FIFO fashion. Display doesn’t
remove the element from the queue; it only shows all the elements. Display always done from front to rear location.

Void traverse(void) Step 1: start.


{ Step 2: check if (front>rear) then,
If(front>rear) Print “underflow”
printf(“\n underflow”); Otherwise
else Step 3: repeat step 4 for i=front to rear step 1
{ Step 4: print a[i]
for(i=front;i<=rear;i++) [end of loop]
printf(“ %d”,a[i]); Step 5: stop.
}
}

Isempty
It is optional operation. It is basically used for internal processing and find out the validity of operation
either it can be performed or not. This process identifies whether the queue is empty or not.
If(front>rear)
printf(‘\n underflow”);

isfull
It is basically used to find out whether the queue is full or not. So that Insertion like operation can be
performed or not.
if(rear==max-1)
printf(“\n underflow”);

Two Types Of Queue :


1. Linear
2. Circular

Diagrammatically Representation Of Queue Operation: - (Linear Queue)


Here because of FIFO technique, two indicators will be used f (front) and rear (r). We initialize by 0 and rear by -1.
 When we enqueue the element in queue, then rear will always be increased by one.
 Here, first we increase the rear & then we enqueue (insert) the element, because initially rear is i-1, we can
not make it 0(zero) because 0 is a legal location of array and -1 can be used that either queue is empty or
not.

 Vidhya Institute of Information Technology 


25
Ideal ‘Data Structure’

Enqueue Operation Representation


Initial queue of 5 elements:

4 10
3 20
2 32
1 25
front 0 52
rear = -1

Enqueue of 10, 20, 30, 40 &50 one by one


Enqueue Enqueue Enqueue Enqueue Enqueue
10 20 30 40 50

104 4 4 4 50 4r
rear=rear+1

rear=rear+1

rear=rear+1

rear=rear+1
40

rear=rear+1
3 3 3 3r 40 3
10
2 2 30 2r 30 2 30 2
1 20 1 r 20 1 20 1 20 1
10 0 r 10 0 10 0 10 0 10 0

Front Front Front Front Front

During Enqueue,10 front will always be pointed to first element in above case it is 0 th location and rear (r) will be
increased by one with every insertion.
10
 After that if we insert or enqueue the element, stack will be “overflow” (when n=r)
DEQUEUE Operation Representation

Technique 1: -
rear 4 50
3 40
2 30
1 20
front 0 10

One by one dequeuing of element from queue.


50 4 50 4 50 4 50 4 f 50 4
front=front+1

front=front+1

front=front+1

front=front+1

front=front+1

40 3 40 3 40 3 f 40 3 40 3
30 2 30 2 f 30 2 30 2 30 2
20 1f 20 1 20 1 20 1 20 1
10 0 10 0 10 0 10 0 10 0

Dequeue Dequeue Dequeue Dequeue Dequeue


10 20 30 40 50

 Vidhya Institute of Information Technology 


10
26
10
Ideal ‘Data Structure’

 Here element is dequeuing from front (f) that’s why front increasing by one when every element is
removed or dequeue from queue.
 Dotted elements represent deleted element.
Ques: When any element is removed from queue and in last stage all elements have been removed
from Queue; even it is showing queue overflow (why)?
 As rule when r arrive at n means queue is full or overflow.
 And in every stage, when element is removing queue always is located at n. So queue will always full
even its locations are empty.
 It is major drawback of queue, that when every element removes from queue, than at this time also
queue is flow, or no space for new element.
 But naturally it is a genuine reason. That when one is removed, surely another can be stored here.
 So now we will remove or dequeue the element with other technique. (Shown below)

TECHNIQUE – 2
 In this special technique when we remove any element then it will be replaced by its next location, and in
this way all elements will be replaced by their next element.
 So in last, a block will become empty and new element can be stored here and rear (r) will decrease by
one.
 So with the help of this technique when queue element dequeued, the new element can be inserted into
the queue, not like before. (technique)
Suppose we have a following queue with 5 elements

rear 4 50
3 40
2 30
1 20
front 0 10
 If element dequeued from queue

50 4r 50 4r 50 4r 50 4r 50 4


40 3 40 3 40 3 40 3 50
front=front+1

front=front+1

front=front+1

front=front+1

3r
front=front+1

30 2 30 2 30 2 40 2 40 2
20 1 20 1 30 1 30 1 30 1
10 0 f 20 0f 20 0f 20 0f 20 0f

Dequeue shifting of shifting of shifting of shifting of


10 20 30 40 50
a[0]=a[1] a[1]=a[2] a[2]=a[3] a[3]=a[4]

Now after removal of 10


Rear decrease by one
So rear not equal to n
That’s why queue is no full
(No overflow)
Easily new element can be inserted at rear.
This process is same with every dequeue.
Technique -2 is better than technique 1

 Vidhya Institute of Information Technology 


27
Ideal ‘Data Structure’

Practical Implementation Of Queue


(By Technique 1)
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define max 10
Int a[max],f=0,r=-1;
void main ()
{
int i, t, ch;
while (1)
{
clrscr();
printf(“\n Queue Operation”);
printf(“\n 1. Enqueue”);
printf(“\n 2 .Dequeue”);
printf(“\n 3 Peek”);
printf(“\n 4 .Display”);
printf(“\n 5 .Exit”);
printf(“\n \n \t\t Enter your choice……….”);
scanf(“%d”, &ch);
switch(ch)
{
case1:
if (r= =max-1)
printf(“\n queue overflow”);
else
{
r++;
printf(“\n enter element which you want to dequeue”);
scanf(“%d”, &a[r]);
/* shortcut = scanf(“%d”, a[++r] ); */
printf(“\n %d element enqueued sucessfully ”,t);
}
break;
case 2:
if (f>r)
printf(“\n queue underflow”);
else
{
printf(“\n %d element is going to technique ”,a[f])
f++;
}
break;
case 3:
if (f>r)
printf(“\n queue underflow”);
else
printf(“\n peek element is :-%d”, a[f]);
break;
case 4:
if (f>r)
printf(“\n queue underflow”);
else
{
printf(“\n queue elements are -:”);
for (i=f; i<=r; i++)
printf(“\n %d”, a[i]);
}
break;
case 5: exit (0);

 Vidhya Institute of Information Technology 


28
Ideal ‘Data Structure’

default:
printf(“\n invalid choice”);
printf(“\n try again with menu based values”);
}// closing of switch();
getch();
}// closing of while loop
}closing of main function & program .
Technique 2
Implementation of technique 2 is exactly similar to technique -1 only case 2 will change that is specified
below (dequeue case)

case 2:
if (r= = -1// f= = n)
printf (“\n queue underflow”);
else
{
printf(“\n %d element is going to technique, ” a[f]);
for (i=f; i<r;i++)
a[i] = a[i+1];
r--;// decrease rear
}
break;
 So after the execution of this case  loop every element shifted to its down location and r will be
decreased by one, so the capacity of queue will increase because in this case now r not equal to n.
 That’s why it is better than technique – 1.
Applications / Uses Of Queue
 In our real life
 Queue of exam forms
 Queue at window of ticket etc.
 System Queue
 System perform various tasks, for processing system maintain different – different types
of queues.
 For example.
 Instruction Queue
 This queue maintains the current instructions which are going to be executed by the
processor.
 Device Queue(I/O queue)
 This queue stores id of all the devices which are currently available within the system.
 Waiting Queue
 When processor executes any processing, and at same times another process comes into
existence, and then it has to wait, so these waiting processes are hold by waiting queue.
 Queue is used in BFS (Breadth First Search) of graph.
 Queue is used in client server computing
 Printing Queue
 This queue holds all the process which is waiting for their turn when any other process
is using printer.
 Queue is also used in level order traversal of binary tree
 Queue plays very important role in processing [by processor]

 Vidhya Institute of Information Technology 


29
Ideal ‘Data Structure’

ALGO
Enqueue (queue, front, rear, max, item)
Step 1: [chek for overflow]
If rear = max-1 then
Display “queue overflow”
Exit
End if
Step2:
[increase one by one]
Set rear = rear +1
Step 3:
[store item at rear location]
Set queue [rear] := item
Step 4 exit
ALGO
Dequeue [queue, front, rear, and item]

Step 1 : [chek for overflow]


If f>=r then
Display “queue overflow”
Exit if
Step 2 : remove item front front
Set item: = queue [front]
Step 3 : [shift all the element to fill deleted value location]
Set I = f
Repeat step 4,5 while i<rear
Step 4 : set queue [i] = queue [i+1]
Step 5 : [increase I by one]
Set i= i+1
Step 6 : [decrease rear by one, because one element dequeued]
Set rear = rear -1
Step 7 : End

Linked list Representation of queue.


 queue can also represented by linked list
 queue works on FIFO
 so, in case of linked list
 so for insertion
 Insert- at – last algo is used
 so for deletion
 Delete from - first algo is used

DEQUE(deck DOUBLE ENDED QUEUE)

special type of queue


 refered as double ended queue
 two types of dequeue
(1) Input Restricted Dequeue
(2) Output Restricted Dequeue
(1) Input Restricted Dequeue
 insertion done at rear
 but deletion can be done at both point
either front or rear
(2) Output Restricted Dequeue
 insertion can be done at Both point either front or rear
 Deletion done at always front

 Vidhya Institute of Information Technology 


30
Ideal ‘Data Structure’

PRIOITY QUEUE
 Special type of queue
 Follow all the rules of queue
 Insert done at rear
 Deletion is not directly specified.
 Deletion is based on priority of element.
 Deletion can be performed any where.
 So when any element is entered, then its priority must be entered.
 Two types of priority queue are here
(1) Ascending Priority Queue
 it effect deletion of element
 lowest priority element will removed
(2) Descending Priority Queue
 It also effect deletion of element.
 Highest priority element will removed
Representation of priority queue
 By Linked List
 By 2-D Array
 By Structure
By Linked List
 every node have three part
 Two data part
 Part 1 : element (e)
 Part 2 : priority (d)
 one address part
 Link/ next : point to the next node
By 2-D Array
Two sub script is used
M one for number element.
N priority of each element
For example
int p[4][2] ;
10 4
20 1
30 3
40 2
By Structure
 As we know, that > structure is an user define data type
 It is a collection of different data type.
 Here, we can use the structure.
 We create a structure
 With two integer elements
 One for element (e)
 One for priority (p)
For e.g.,
Struct queue
{
int e;
int p:
};
struct queue q [4];
0[10][500]
1[20][-40]
2[30][2]
3[40][50] priority

 Vidhya Institute of Information Technology 


31
Ideal ‘Data Structure’

CIRCULAR QUEUE
 It is a special type of queue like priority queue .
 queue will cyclic form is called circular queue.
 When front and rear combine together it forms circular queue.
 used to eliminate overflow situation.
 Endless queue.
 Front & rear is used.

#include<stdio.h>
#include<conio.h>
#include<process.h>
#define max 5
int a[max],front=-1,rear=-1;
void enqueue(void);
void dequeue(void);
void peek(void);
void traverse(void);
void main()
{
int ch;
while(1)
{
clrscr();
printf("\n 1. Enqueue");
printf("\n 2. Dequeue");
printf("\n 3. Peek");
printf("\n 4. Traverse");
printf("\n 5. Exit");
printf("\n Enter the choice....");
scanf("%d",&ch);
switch(ch)
{
case 1: enqueue(); break;
case 2: dequeue(); break;
case 3: peek(); break;
case 4: traverse(); break;
case 5: exit(0);
default: printf("\n INVALID CHOICE...");
}
getch();
}
}
ALGO FOR INSERTIION
void enqueue(void) Step 1: start.
{ Step 2: check if (front=0 And rear=max-1)
if((front==0 && rear==max-1)||(front==rear+1))
OR (front=rear+1)) then,
printf("\n overflow");
Print “overflow”
else
Otherwise
{ if(rear==-1)
Step(a) check if(rear=-1) then,
{
set rear=0.
rear=0;
front=0; set front=0.
} Again check if(rear=max-1) then,
else if(rear==max-1) Set rear=0.
rear=0; Otherwise
else Set rear=rear+1;
rear++; [end of if]
printf("\n enter the element "); Step 3: read an element a[rear].
scanf("%d",&a[rear]); [end of if]
} Step 4: stop.

 Vidhya Institute of Information Technology 


32
Ideal ‘Data Structure’

void dequeue(void)
{ ALGO FOR DELETION
if(front>rear) Step 1: start.
printf("\n underflow "); Step 2: check if (front=-1) then,
else Print”underflow”
{ Otherwise
printf("\n Dequeued element %d",a[front]); Step 3: print “dequeued element ”a[front].
if(front==rear) Step 4: check if (front=rear) then,
{ Set front=-1;
front=-1; Set rear=-1.
rear=-1; Again check (front=max-1) then,
} Set front =0.
else if(front==max-1) Otherwise
front=0; Set front=front+1.
else [end of if structure]
front++; Step 5: stop.
}
}

void peek(void)
{ ALGO FOR TRAVERSE
if(front>rear)
printf("\n underflow "); Step 1: start.
else Step 2: check if front=-1 then,
printf("\n Dequeued element %d",a[front]); Print “ underflow”.
} Otherwise
Step 3: check if (front<=rear) then,
void traverse(void) Step 4: Repeat step (a) for i=front to rear ,
{ Step (a) print a[i]
int i; [End of loop]
if(front>rear) Otherwise
printf("\n underflow "); Step 5: repeat for step (6) for i=front to max-1
else Step 6: print a[i]
{ [End of loop]
if(front<=rear) Step 7: repeat for step (8) for i=0 to rear
{ Step 8: print a[i]
for(i=front;i<=rear;i++) [End of loop]
printf(" %d",a[i]); [end of if]
} Step 9: Stop.
else
{
for(i=front;i<=max-1;i++)
printf(" %d",a[i]);
for(i=0;i<=rear;i++)
printf(" %d",a[i]);
}
}
}
Application of Queue

1. Round robin techniques for processor scheduling is implemented using queues.


2. All types of customer service(like railway reservation) center software designed using queue to store
customer information.
3. printer server routines are designed using queue.

 Vidhya Institute of Information Technology 


33
Ideal ‘Data Structure’

MEMORY ALLOCATION
We write our program to perform any task our program will always store some amount of data and for
storing these values memory is required so, here memory must be allocation before its use.
There are two types of memory allocation:

 STATIC M EMORY ALLOCATION


 DYNAMIC MEMORY ALLOCATION

STATIC MEMORY ALLOCATION


It is used when size of memory is already known in advance
 Size of block is always fixed.
 Memory size can not be increased or decreased at run time.
 Generally in these allocations blocks are allocated continuously with in memory
 Where fixed amount of memory is required, this type of allocation is used.
 Memory management in this static is entirely depend on compiler means compiler
 Automatically allocate or deallocate the memory during program execution.
 Also called “compile time memory allocation”
 So increase the reability of our program.
 Reduce the complexity of our program.
 No burden of programmer of memory management
 Easy to implement.
 Generally no use to pointers.
 Array type of memory allocation is called static memory allocation
 Data can be accessed directly with unique position number called index no.
 No specially functioning is required.

DRAW BACK
When the size of memory block means if number of blocks is not known before then static is not better to use.
 Size is not known it is based on run time
 So either we specify less or higher size.
 If we specify less size:
 Then no more data can be interred at run time we can not increase its size so our program will
become failure in case of input data.
 We specify huge size:
Then if user entered less amount of data and we are not able to decrease the size of memory at
runtime then,
 “Wastage of memory” our memory will become waste, no any another program can use it so
this thing reduce the performance of our system so we can not specify large size.
 If contains memory is not available in memory then static memory allocation become fail,
 That’s why because of this drawback dynamite memory allocation is used.

DYNAMIC MEMORY ALLOCATION


It is just apposite of static memory allocation.
 It is an advance from of static memory allocation.
 It is used when the size of memory is known in advance.
 Memory size means no. of blocks can be easily increased or decreased at run time.
 Generally in these allocations blocks are allocated at random locations with in memory
 When dynamic (changeable) amount of data is required, then this type of allocations is use.
 It this dynamic memory allocations entire memory management is depend on programmer
means programmer has to manually allocate or deallocate the memory during program execution
by coding.
 Also called “run time memory allocation” Because no any amount of memory is allocated at
compile time all memory will allocate at run time.

 Vidhya Institute of Information Technology 


34
Ideal ‘Data Structure’

Basically used to save the large amount of memory it size of memory is not
known.

DRAW BACK
 Increase complexity of our program.
 Decrease readability of program.
 Concept of pointer is always used, which make program compiler.
 No. easy to implement.
 Specially functioning is required to allocate or deallocate the blocks memory like.
 malloc, calloc, realloc, or free.
 Because memory already allocated at compile time.
 Increase the readability of our program.
 Reduce the complexity of our program.
 No burden of programs of memory management easy to implement..
 Generally no use of pointers.
 Array type of memory allocation is called static memory allocation.
 Data can be accessed directly with unique position number called index no.
 No. specially functioning is required.
 When the size of memory block means it number of block are not known before the static is not
better to use.
 Because When we static memory allocations then we have to specify the size.
 Size in not known it is based on run time.
 So either we specify less size or higher size.
 If we specify less size.
 Then no more data can be entered run time we can not increase its size so our program will
become failure in case of input data.

SOME CONCEPT
Question How dynamically memory is allocated?
Answer Here we will first of all

 Specify the structures of memory block where we want to store data these blocks are called
NODE.
 As per requirement multiple NODES are created.
 We cannot these NODES one by one or when we create the block at the same time we can
connect blocks.
 For memory allocation different types of function are used.
 Malloc : for allocating single block.
 Calloc : for allocation multiple blocks [increase].
 Free: remove allocated blocks from member.
 Here we made the blocks after that we have connect these NODES.
So for connecting special types of NODE structure is required [as follow]

DATA PART
 This part contain all those which we want to store in memory.
 Data part can also further divided in multiple data part
such as stud roll no, name, percentage because generally
we create node to hold multiple data about any entity
like student book, EMP.

ADDRESS PART
 It we say that after creating the NODES we have to connect them so for connecting always
pointer is required here these above address part is pointer which hold the address of next
NODE so generally it is named next pointer.

 Vidhya Institute of Information Technology 


35
Ideal ‘Data Structure’

 So any always have these above two parts data part and address part these both parts can be
multiple but depend on requirement.

Question what will be the type of pointer next either int long float char.?
Answer Here NODE address part hold the address of next entire node it does not hold address of
individual data part so that‘s why
The type of next pointer is node type itself and it is a part of node itself means it is a member of
NODE structure.
Such type of structure called Self Referential Structure.

SELF RFERENTIAL STRUCTURE


Suppose we want to create a NODE structure which can hold single integer value and address of next
NODE, then practical implemented of such structure will be:
struct list
{
int no;
struct list * next;
};

NODE structure graphically:

Here next is a pointer, whose type is some as structure type,


Such type of structure is called referential structure.
We create multiple nodes (by malloc)

X represent NULL
The move structure is called Linked List

Dynamic Memory Allocation Function

Sizeof()
The size of function is a unary argument function. This function the size of argument in the term of bytes.
The argument can be a variable , array or any data type(int, float, char…)

Example:- sizeof(int);

malloc()
This function is used to allocate the memory space. Of specified size or data type and gives the starting
address to pointer variable.

Example:- ptr=(int*)malloc(10);
This allocate 10 bytes of memory space area to the pointer variable ptr of int type.

ptr=(int*)malloc(10*sizeof(int));

This allocate the memory space 10 times, that holds an int data types. The based address is stored in the pointer
variable ptr.
Example
Void main()
{
Int i,*a;

 Vidhya Institute of Information Technology 


36
Ideal ‘Data Structure’

a=(int*) malloc(5*sizeof(int));
for(i=0;i<5;i++)
{
printf(“\n enter the %d number”,i+1);
scanf(“%d”,(a+i));
}
for(i=0;i<5;i++)
printf(“ %d”,*(a+i));
getch();
}

Calloc()
The calloc() function is used to allocate multiple blocks of memory. This has two arguments.
ptr=(int *) calloc(5,2);
This allocate 5 blocks of memory, each block contain 2 byte memory and the starting address is stored in
the pointer variable ptr which is of type int.
It is use for allocating the memory space for array and structure.
struct student
{
int roll;
char name[30];
};
int rec=50;
ptr=(student *)calloc(rec,sizeof(student));

This allocate the memory space for 100 blocks and each block contain memory space the occupied by the
structure.

Free()
for effective use of the memory we can release the memory space that is not required. We can use free
function for releasing the memory space.

Example :- free(ptr);

realloc()
there are two possibilities when we want to change the size of the block.
In the first case we want the more memory space comparatively to allocate memory space.
In the second case the allocate memory space is more then the required memory space.. For the changing
size of memory block we can use the function realloc();

Example :- ptr=realloc(ptr, newsize);

 Vidhya Institute of Information Technology 


37
Ideal ‘Data Structure’

LINKED LIST
A linked list is a collection of connected nodes, where each node information about an
entity.

These are different types of list.


Single linked list

Doubly linked list

Singly circular linked list

Doubly circular linked list

Some concepts
 Here every node the address of next node but who will hold the address of first node
 So here we have to define another pointer that point to first node here we use start and t name
pointer that hold the address of first node.
 When t move to next node or another node then how they can move again to first node so start
pointer is used always pointer to first node.

 Here X null represent ending of list because last node does not hold address of any node.

Operations on linked list


1. Creation Of A List;
2. Traversing Or Display Of A List
3. Counting The Node In The List
4. Insertion In The List
5. Deletion From A List
6. Searching Of A Node In The List

 Vidhya Institute of Information Technology 


38
Ideal ‘Data Structure’

SINGLY LINKED LIST


Algorithm to create a linked list :
let node in a linklist contains a field DATA and another field NEXT pointer which contains the address of
next node. the pointer “START” will always point to the first node.

step 1: Begin.
step 2: declare struct node *n,*t.
step 3: if STAR=NULL, then: {if list is empty ‘START’ contains NULL}
(a) set start=assign memory address using malloc function
(b) set start->info =data
(c) set start-> next=NULL;
step 4: else
(a) set t=start.(assign the address of first node in another pointer)
(b) repeat while loop t->next !=NULL
t:=t->next;
(End of while loop)
(c) (add node at the end) set n=(assign the memory using malloc function)
(d) set n->info =data;
(e) set n->next=NULL;
(f) set t->next=n.
[end of if structure]
step 5: stop.

Function Definition

void create(void)
{
struct node *t=start;
struct node *n=(struct node*)malloc(sizeof(struct node));
printf(“\n enter the information”);
scanf(“%d”,&n->info);
n->next=NULL;
if(start==NULL)
start=n;
else
{
while(t->next!=NULL)
t=t->next;
t->next=n;
}
}

10 20 30 40 50

start A B C D E

With the help of add last concept we can create a linked list.

Insertion in singly /linear linked list


“get node process”
 In case of dynamic memory allocation memory block can be easily inserted or deleted
 So here procedures are given which shows how node or memory block can be inserted.
 In linked list node can be inserted at these different locations:
 1 insert at first
 Insert at last

 Vidhya Institute of Information Technology 


39
Ideal ‘Data Structure’

 Insert at mid
Before defining the procedures consider following points:
 Starts & t always point to the first node of a list if list does not exist these pointers contain
NULL
 for operational purpose start or t can be moved in linked list at a node and for convenient t is
used to perform operations so it is moved in linked list
 [according to choice this pointers can used]
 [n] pointer is also used it contain the want to insert in a linked list.

structure is :
struct node
{
int info;
struct node * next;
};
//typedef struct node slist;

Insert at front
function
void addfront(void) Algorithm for insert at the front of the linked list
{ step 1 : create a new node n.
struct node *n=(struct node*)malloc(sizeof(struct node)); Step 2 : check if (start=NULL) then,
printf(“\n enter the information ”); set Start : = n.
scanf(“%d”,&n->info); ohterwise
n->next=start; Step 3: set n -> next : = start.
start=n; Step 4: set start : = n.
printf(“\n inserted at front”); [end of if structure]
} step 5: stop.

in condition first (if linked list have no node) then 5 x


start=n.
n is new node start (n)

n Start(t)
5 X 10 B 20 C 30 D 40 X
A B C D
n -> next = start

[After execution of above statement]


n Start(t)

5 A 10 B 20 C 30 D 40 X

A B C D

Step 3: start=n
start is maintained to hold the address of first node before first node was 10 but after
insertion n is become first node so start must also point to the first node that’s why move t to the n , after that
structure will be:

5 A 10 B 20 C 30 D 40 X

n A B C D
start

 Vidhya Institute of Information Technology 


40
Ideal ‘Data Structure’

Insertion at last
View at list point we want to insert the node at the last then we follow given step
step 1: create a new node n(by malloc function). and insert the information in info part
step 2: set n ->next:=NULL;
Step 3: check if (start =NULL) then,
Start = n;
otherwise
Step 2: repeat step a while (t ->next ! =NULL)
(a) set t = t ->next;// move t to next node
[end of while]
Step 3: set t ->next = n;
[end of if structure ]
step 4: stop.

void addlast(void)
{
struct node *t;
struct node *n=(struct node*)malloc(sizeof(struct node));
t=start;
printf(“\n enter the information ”);
scanf(“%d”,&n->info);
n->next=NULL;
if(start==NULL)
start=n;
else
{
while(t->next!=NULL)
t=t->next;
t->next=n;
}
}

 Vidhya Institute of Information Technology 


41
Ideal ‘Data Structure’

INSERT AT MID
Node can be easily inserted in the linked list at mid also (dynamic memory allocation)
 Node can be inserted by two techniques.
 By node value
 By node number
 In this technique two nested technique also used
 By node value [before node value, node][after node value ,node]
 By node number [before node number, node] [after node number, node]
 Generally “After Node Value” technique is preferred.
 For node values & variable is used which hold the value of node after which node is inserted.
void addaftcons(void)
Algorithm: after node value new node insertion {
step 1: Create a new node n by malloc function.
int data;
insert the information in info part.
struct node *n=(struct node*) malloc(sizeof(struct node));
step 2: Read data value after which you want to
struct node *t=start;
insert the node. printf(“\n enter the information”);
Step 3: Check if (start = NULL) then,
scanf(“%d”,&n->info);
set Start : = n.
printf(“\n enter the information after which you
otherwise
want to insert ”);
Step 4: Repeat step (a) while (t!=NULL) scanf(“%d”,&data);
step a: check if(t->info=data) then,
while(t!=NULL)
stop searching/ break;
{
otherwise
if(t->info==data)
set t:=t->next; break;
[end of if structure]
else
[end of while]
t=t->next;
step 5: check If(t=NULL) then,
}
print ” not found the data ” if(t==NULL)
goto step 7.
{
[end of if structure]
printf(“\n constant not fount ”);
step 6: set n->next:=t->next.
return;
step 7: set t->next=n. }
[end of if structure]
n->next=t->next;
step 8: stop.
t->next=n;
Description printf(“\n node inserted…….”);
}

 Vidhya Institute of Information Technology 


42
Ideal ‘Data Structure’

Counting the nodes in a linked list


In this operation count() function is use to count total number of nodes.
Function
int counting(void) step 1: begin.
{ step 2: declare : struct node *t=start;
struct node *t=start; step 3: set count =0.
int count=0; step 4: repeat step (a & b) while (t!=NULL),
while(t!=NULL) a) set count=count+1
{ b) set t:=t->next
count++; [end of while]
t=t->next; step 5: print count.
} step 6: end.
return(count);
}
1 2 3 4 5
0 0 0 0 0
A B C D E

1 2 3 4 5

Inserted Mid Technique By After Node Number


 Suppose user input node number rather node value then procedure is some only loop will change we have
to move the start to the node by its number (n).
 User will input n Point keep in mid this n must not greater than total nodes in the linked list
void addaftpos(void)
{
int pos,ctr=1;
struct node *t=start;
struct node *n=(struct node*)malloc(sizeof(struct node)); algorithm for insert a node after given position
printf(“\n Enter the information of new node ”); Step 1: create a new node n by malloc function.
scanf(“%d”,&n->info); Read info.
printf(“\n Enter the position …..”); Step 2: read pos (position).
scanf(“%d”,&pos); Step 3: check if (pos>count()) then,
if(pos>count()) print “invalid value ”
printf(“\n invalid position ”); otherwise
else Step 4: Repeat step (a & b ) while (ctr<pos)
{ (a) set ctr=ctr+1
while(ctr<pos) (b) set t:=t->next;
{ [end of while]
ctr++; Step 5: set n->next:=t->next.
t=t->next; Step 6: set t->next=n.
} [end of if structure]
n->next=t->next; Step 7: stop.
t->next=n;
printf(“\n node inserted after %d position ”,pos);
}
}
Insert at given position
 In this technique user will input node number and on it node should inserted.
 So that’s why we have to move t to that previous node (s) but it’s before we want to insert new node.
while(ctr<pos-1)
{
ctr++;
t=t->next;
}
n->next=t->next;
t->next=n;
printf(“\n Node Inserted on %d Position ”,pos);

 Vidhya Institute of Information Technology 


43
Ideal ‘Data Structure’

DELETION IN LINKED LIST


 linked list is a Dynamic Memory Allocation
 as per requirement memory can be allocated or deallocated.
 as per insert the node , similarly node can be easily deleted from the list according to our requirement.
 For deletion of a node free()function is used
Syntax
Free (t);
Free function remove block from the memory whose address is hold by the t pointer.
Deletion operation can also be done at these points
1. Delete From First
2. Delete From Last
3. Delete From Mid
 here before implementing this procedure keep follow points:

ptr, pointer may be used to hold intermediate addresses of node just like pointer in insertion
if start is NULL , means no node is available for delete
If start ->next = NULL means it is only a single node directly delete it with out consider first last mid
locations.
Delete from first
void delfront(void)
{ Step 1 check if (start = NULL) then,
struct node *t=start; Print ”list is empty”.
if(start==NULL) Step 2 Again check if (start ->next = NULL) then,
printf(“\n empty linked list”); free (t).
else set Start := NULL.
{ otherwise
start=start->next; set Start := start ->next.
free(t); [end of if structure]
printf(“\n node deleted from front ”); Step 4 free (t).
} Step 5 stop.
}
Description
Step 1: if start is NULL then
No node to delete
Step2: if it is single node
Directly delete it

Step 3: move starts to next node


Because when we delete first node
Second node will become first node so after above line start point to this new first Node
t in now pointing to first node as before
Step 4: free (t)
By this statement first node pointing by t will remove from memory t point to garbage value
 But start always point to first node
 At that movement new first node is pointed by start.
 Here we can also move t to the next node free t and move start to t
Both are same technique any one can be used

PICTORIAL REPRESENTATION

 Vidhya Institute of Information Technology 


44
Ideal ‘Data Structure’

DELETE FROM LAST


void dellast(void)
{
struct node *t=start; Step 1: check if (start = NULL) then,
if(start==NULL) Print“\n list is empty”.
printf(“\n Undeflow ”); Step2: again check if (start ->next = NULL) then,
elseif(start->next==NULL) declare Free (t);
{ set Start : = NULL
free(t); otherwise
start=NULL; Step 3: repeat step (a) while (t->next->next! = NULL),
printf(“\n last single node deleted”); set t := t ->next;
} [end of while]
else Step 4: declare free (t ->next);
{ Step 5: set t ->next = NULL;
while(t->next->next!=NULL) step 6: stop.
t=t->next;
free(t->next);
t->next=NULL;
}
}

Description
Step 1: if start is NULL then
No node to delete
Step 2: if start of next = NULL means
Free start or remove it
Step 3: otherwise
Move start to second last node
By using loop
We move last to second last because when we arrive at second last node we will directly remove
its address part node
Assign its next to NULL, so it will become the last node of linked list
Note: If we move to last node then for assigning NULL to second last node then how we will move
backward.

 t pointing to 40 because its next -> next is NULL


 As defined that if we run the loop for last node then We can easily remove it
 But its previous node address part must contain NULL So we have to move to the previous node the is
not possible because every Node the hold the address of next node but node does not hold the address of
previous node.
 So because of this reason we move t to the second last node

start
(t)

start
(t)

 Vidhya Institute of Information Technology 


45
Ideal ‘Data Structure’

DELETION FROM MID


 Node can be easily removed from the list from mid also (dynamic memory allocation)
 Node can be deleted by two techniques
 By node value
 By node number
 Again in this technique two nested technique also used
 By node value [before node value, node][after node value ,node]
 By node number [before node number, node][after node value, node]
 Generally after node value deletion technique is preferred
 for node value & variable is used which contain the value of node which we want to delete
Point to consider:
any node which we want to delete we have to move our start pointer to its previous node so, that we can link
it with delete node->next node otherwise linked list will become break.

Algorithm Delete From Mid By Node Value


void delfrmcons(void)
data = hold value of node which we want to delete {
Step 1: check if (start = NULL) then, int cons;
Print“list is empty” struct node *t=start,*ptr;
Step 2: again check if (start ->next = NULL AND struct node *n=(struct node*)malloc(sizeof(struct node));
printf(“\n enter the information ”);
start ->info = data) then,
scanf(“%d”,&n->info);
declare Free (t). printf(“\n enter the constant ”);
set Start = NULL. scanf(“%d”,&cons);
otherwise while(t!=NULL)
Step 3: repeat step (a) While (t!=NULL) {
step (a) check if(t->info=data) then, if(t->info==cons)
goto step 7 break;
otherwise else
set ptr=t. {
set t:=t->next. ptr=t;
(end of if structure) t=t->next;
}
[end of while]
}
Step 6 check if (t= NULL) then, if(t==NULL)
print”data not found”. {
[end of if structure] printf(“\n not found…..”);
step 7: set ptr->next=t->next. return;
step 8: release node t. }
[end of if structure] ptr->next=t->next;
step 9: stop. free(t);
}
Description
if we want to delete the data 30 from link list. then we required pointer t , pointer ptr
t=pointer point to the node which we want to delete
ptr=previous pointer of t pointer
t t->next

“node deleted from mid successfully”

 Vidhya Institute of Information Technology 


46
Ideal ‘Data Structure’

DELETE FROM POSITION

PTR T T->NEXT

void delfrmpos(void)
{
struct node *t=start,*ptr; Algorithm
int pos, ctr=1; Step 1: start.
printf(“\n Enter The Position Of Step 2: set pointer struct node *t=start and *ptr.
Node You Want To Delete”); Step 3: set ctr=1 and read pos.
scanf(“%d”,&pos); Step 4: check if(pos>count()) then,
if(pos>count()) Print ”invalid position”.
printf(“\n invalid position”); Otherwise
else Step 5: repeat step 6,7 while(ctr<pos)
{ Step 6: Set ptr=t.
while(ctr<pos) Step 7: set t:=t->next.
{ [end of loop]
ptr=t; Step 8: set ptr->next:=t->next.
t=t->next; Step 9: free(t).
} [end of loop]
ptr->next=t->next; Step 10: stop.
free(t);
printf(“\n node deleted…”);
}
}

 Vidhya Institute of Information Technology 


47
Ideal ‘Data Structure’

DELETION OF ENTIRE LIST


 It is Dynamically Allocation
 User allocate two memory by malloc () or calloc ()
 It is also a task to user to again to remove these nodes from memory
 Because this block does not remove automatically user has to remove then manually.
 So when our program become complete and going to finish then programmers has to explicitly remove these
all nodes from list.
Procedure
Start = t;
While (start ! = NULL)
{
start = start ->next;
free (t);
t= start;
}

Start=start->next

Then start=NULL.
LINKED LIST DELETED

 Vidhya Institute of Information Technology 


48
Ideal ‘Data Structure’

Reverse of A Linked List

void reverse(void)
{ algorithm
struct node *t=start,*start1=NULL; step 1: start.
while(start!=NULL) step 2: declare *t=start,*start1=NULL.
{ step 3: repeat step () while(start!=NULL),
t=start; step (a) set t:=start.
step (b) set start:=start->next
start=start->next;
step (c) set t->next:=start1;
t->next=start1; step (d) set satrt1=t.
start1=t; [end of loop]
} step 4: set start=start1.
start=start1; step 5: stop.
}

start

start1

start1

start1

start1

start1

 Vidhya Institute of Information Technology 


49
Ideal ‘Data Structure’

CIRCULAR LINKED LIST


 It is a special type of linked
 The address part of the last node generally holds NULL to indicate end of list.
 We use this address part to hold address of a node.
 A circular linked list does not contain NULL is any address part.
 The address part of last node hold the address of first node, that type of list is known as singly circular linked
list.

ADVANTAGE
From the last node we can directly move to first node because here last node hold’s the address of first value.
So here direct movement of pointer from fast node to first node is easily possible .

General Singly Linked List Representation

TRAVERSAL OF SINGLY CIRCULAR LINKED LIST


Traversal refers to access or process all the elements of linked list or data structure.
Algorithm
void traverse(void)
step 1: start.
{
step 2: set struct node * t=start; struct node *t=start;
step 3: check if(start= NULL) then, if(start==NULL)
print “ empty linked list” printf(“\n linked list is empty”);
otherwise else
step 4: repeat step (a &b) while(t->next!=start) {
step (a) print t->info while(t->next!=start)
step (b) set t=->next. {
[end of loop] printf(“ %d”,t->info);
t=t->next;
step 5:print t->info
}
[end of if structure] printf( ’’ %d “,t->info);
step 6: stop. }
}

 Vidhya Institute of Information Technology 


50
Ideal ‘Data Structure’

Here t -> next equal to start


A=A
 Loop will not run
 So here 40 is not print or process
 Manually with out loop it has to processed
 [So step 5 is used]
 Display (t ->info) (40)
 In this way circular linked list traversal Performed

INSERTION IN SINGLY CIRCULAR LIST


1. Insert At First
2. Insert At Last
3. Insert At Mid
is a new node pointer which is pointing to new node which we want to insert in linked list.
Insert At First
Algorithm

step 1: start. void addfront(void)


step 2: declare struct node *t. {
step 3: set t=start. struct node *t=start;
step 4: create a new node n by malloc function. struct node *n=(struct node *)malloc(sizeof(struct node));
and enter the information in info part. printf(“\n enter the information ”);
step 5: check if(start=NULL) then, scanf(“%d”,&n->info);
set start=n. if (start = = NULL)
set start->next=start {
otherwise start = n;
step 6: set n->next=start. start->next=start;
step 7: repeat step (a) while(t->next!=start) }
step (a) set t:=t->next. else
[end of loop] {
step 8: set t->next=n. n->next=start;
step 9: set star=n. while(t->next!=start)
[end of if structure] t=t->next;
step 10: stop. t->next=n;
start=n;
}
}

 Vidhya Institute of Information Technology 


51
Ideal ‘Data Structure’

INSERT AT LAST
Procedure:
void addlast(void)
{ step 1: start.
struct node *t=start; step 2: declare struct node *t.
struct node *n=(struct node *)malloc(sizeof(struct node)); step 3: set t=start.
printf(“\n enter the information ”); step 4: create a new node n by malloc function.
scanf(“%d”,&n->info); and enter the information in info part.
if (start = = NULL) step 5: check if(start=NULL) then,
{ set start=n.
start = n; set start->next=start
start->next=start; otherwise
} step 6: set n->next=start.
else step 7: repeat step (a) while(t!=NULL)
{ step (a) set t:=t->next.
n->next=start; [end of loop]
while(t->next!=start) step 8: set t->next=n.
t=t->next; [end of if structure]
t->next=n; step 9: stop.
}
}

INSERT AT MID
This concept is exact similar to the insertion singly linked because in mid three is no any difference
So same procedure can be followed
 Node can be easily inserted in the linked list at mid also (dynamic memory allocation)
 Node can be inserted by two techniques.
(i.) By node value
(ii.) By node number
By node value
 Generally “After Node Value” technique is preferred
 For node values & variable is used which hold the value of node after which node is inserted.
Algorithm: after node value new node insertion
step 1: create a new node n by malloc function. Insert the information in info part.
step 2: read data value after which you want to insert the node.
Step 3: check if (start = NULL) then,
set Start : = n;
set start->next=start
otherwise
Step 4: Repeat step (a) while (t->next!=start)
step a: check if(t->info=data) then,
stop searching/ break;
otherwise
set t:=t->next;
[end of if structure]
[end of while]
step 5: check If(t->next=start and t->info !=data) then,
print ” not found the data ”
goto step 8.
[end of if structure]
step 6: set n->next:=t->next.
step 7: set t->next=n.
[end of if structure]
step 8: stop.

 Vidhya Institute of Information Technology 


52
Ideal ‘Data Structure’

Function
void addaftcons(void)
{
int data;
struct node *n=(struct node*) malloc(sizeof(struct node));
struct node *t=start;
printf(“\n enter the information”);
scanf(“%d”,&n->info);
printf(“\n enter the information after which you want to insert ”);
scanf(“%d”,&data);
while(t->next!=start)
{
if(t->info==data)
break;
else
t=t->next;
}
if(t->next==start && t->info!=data)
{
printf(“\n constant not fount ”);
return;
}
n->next=t->next;
t->next=n;
printf(“\n Node Inserted…….”);
}

 Vidhya Institute of Information Technology 


53
Ideal ‘Data Structure’

Counting the nodes in a linked list


In this operation count() function is use to count total number of nodes.
step 1: begin.
int counting(void) step 2: declare : struct node *t=start;
{ step 3: set count =0.
struct node *t=start; step 4: repeat step (a & b) while (t->next!=start),
int count=0; (a) set count=count+1
while(t->next!=start) (b) set t:=t->next
{ [end of while]
count++; step 5: print count+1.
t=t->next; step 6: end.
}
return(count+1);
}

Inserted mid technique by after node number


 Suppose user input node number rather node value then procedure is some only loop will change we
have to move the start to the node by its number (n).
 User will input n
 Point keep in mid this n must not greater than total nodes in the linked list
 Use following procedure
Insert At Mid After Node No.
Algorithm for insert a node after given position
step 1: create a new node n by malloc function. insert the information in info part.
step 2: read pos (position).
Step 3: check if (pos>count()) then,
print “invalid value ”
otherwise
Step 4: Repeat step (a & b ) while (ctr<pos)
(a) set ctr=ctr+1
(b) set t:=t->next;
[end of while]
step 5: set n->next:=t->next.
step 6: set t->next=n.
[end of if structure]
step 7: stop.
void addaftpos(void)
{
int pos,ctr=1;
struct node *t=start;
struct node *n=(struct node*)malloc(sizeof(struct node));
printf(“\n enter the information of new node ”);
scanf(“%d”,&n->info);
printf(“\n enter the position after you want to insert the node ”);
scanf(“%d”,&pos);
if(pos>count())
printf(“\n invalid position ”);
else
{
while(ctr<pos)
{
ctr++;
t=t->next;
}
n->next=t->next;
t->next=n;
printf(“\n node inserted after %d position ”,pos);
}
}

 Vidhya Institute of Information Technology 


54
Ideal ‘Data Structure’

Insert At Given Position


 It is one of the compiler logic.
 In this technique user will input node number and on it node should inserted.
 So that’s why we have to move t to that previous node (s) but it’s before we want to insert new node.
while(ctr<pos-1)
{
ctr++;
t=t->next;
}
n->next=t->next;
t->next=n;
0printf(“\n node inserted on %d position ”,pos);
DELETION OF A NODE IN SINGLY CIRCULAR
 Similar to General List.
 Node can be deleted at three different locations.
 Here all procedures are same as in general linked list but w have to consider the address in last node
of first node, remaining are same.
Deletion points
1. Delete from list
2. Delete from last
3. Delete from mid
Delete From List
step 1: start
step 2: check if (start=NULL) then, void delfront(void)
print “linked list empty”. {
step 3: check if (start->next=start) then, struct node *t=start;
declare free(t) if(start==NULL)
set start=NULL. printf(“\n linked list empty”);
otherwise else if(start->next==start)
Step 4: repeat step(a) while(t->next!=start) {
step (a) t:=t->next. free(t);
[end of loop] start=NULL;
step 5: set start=start->next. }
step 6: declare free(t->next). else
step 7: set t->next=start. {
[end of if] while(t->next!=start)
step 8: stop. t=t->next;
start=start->next;
free(t->next);
t->next=start;
}
}

Step 1: Set t pointer at the start node

Step 2: move the pointer t at the last node.

Step 3: move start to the next node

Step 4: delete next node from t pointer means delete the first node.

Resulting linked list

 Vidhya Institute of Information Technology 


55
Ideal ‘Data Structure’

Delete from last


void dellast(void)
step 1: start.
{
step 2: check if (start=NULL) then,
struct node *t=start;
print “linked list empty”.
if(start==NULL)
step 3: check if (start->next=start) then,
printf(“\n linked list empty”);
declare free(t)
else if(start->next==start)
set start=NULL.
{
otherwise
free(t);
Step 4: repeat step(a) while(t->next->next!=start)
start=NULL;
step (a) t:=t->next.
}
[end of loop]
else
step 5: declare free(t->next).
{
step 6: set t->next=start.
while(t->next->next!=start)
[end of if]
t=t->next;
step 8: stop.
free(t->next);
t->next=start;
}
}

Step 1 set t pointer on start

Step 2 move pointer t on second last node

Step 3 delete last node means free(t->next)

Step 4 resulting linked list

Delete From Mid


This operation is exact similar to the deletion from mid in singly linked list.
Because in the mid of list these is no any difference between singly or singly circular linked list.
Doubly Linked List
 It is also known as “2 Way"Linked List.
 It is called doubly because, every node contain double contain.
 Structure of node of doubly linked list. struct node
{
struct node *back;
int info;
struct node *next;
};

 Description of structure of above node:

 Vidhya Institute of Information Technology 


56
Ideal ‘Data Structure’

 Basically his node divided in three major parts.


1. Address part - I
2. Address parts II
3. Data part.
Address part I
This part holds the address of “next node” as in singly linked list.
It is a pointer of node type itself
For Conveniency it is name d = “next”
Address part II
This part differentiate singly with doubly for convenciency it is named”pre”.
Linked list
It is another pointer of node type itself it holds the address of “previous node”.
It is not necessary that ad-1 is used to hold address of next node and ad – 2 hold the address of previous node, it is
arbitrary notation.
Data Part
 It is a main part of node.
 It contains data or information which we want to hold by the node.
 It may be subdivided.
 Different type of divisions may be there.

Question: - why it is called 2 way linked list?


Answer:- 2-Way is called because two ways are here to move with in linked list, but in singly then is only
one way so it is called one way list means.
Both side movement is possible because, every node the address of next node and address of
previous node also.
Any pointer can be easily moved to next node or previous node so it is called 2- way linked list.
TRAVERSALS IN DOUBLY LINKED LIST
1. FORWARD TRAVERSAL
2. BACK WARD TRAVERSAL
FORWARD TRAVERSAL
It is exact similar to the traversals of singly linked list:
while (t! = NULL)
{
printf (“\n % d”, t ->info);
t = t ->next;
}
In this traversals start will move one by one to next node and process its data part.
BACK WARD TRAVERSAL
It is also called recursive traversals
o It is also called opposite traversals
o Here data element is processed in recursive order.
o Every node hold previous node address also that’s why from last node we can move to first node.
Procedure:
Step 1: move t to last node not to its address part that is NULL.
Step 2: t traversals from here to back side by using “t” pointer address part.
Technical Procedure:- “TECHNIQUE 1”
Step 1: while (t ->next! = NULL);
t = t ->next;
Step2: while (t ! = NULL)
{
rintf (“\n %d”, t ->info);
Step 3: t = t->back;
}
Above procedure is of back ward traversals description:

 Vidhya Institute of Information Technology 


57
Ideal ‘Data Structure’

Description:
Step1: For back ward traversals:
 First of all we have to move any pointer at the last node of the linked list so we can move in
backward direction.
 Here one point should consider that moves to last node not its address part because
 Address part of last node is always NULL
 And when we arrive at NULL not possible to move back ward.
Step 2: loop for move to the NULL of First Node back (Previous) address part.
Step 3: t = t-> back;
Statement move from previous node to current node one by one until NULL occurs.

“TECHNIQUE 2”
 Previous technique 1 takes more time and require two steps.
 One loop move for forward.
 One loop for move backward.
 Time consuming process if no. of node increases
 Generally one loop must be there to traversals the data parts of nodes.
 This is accomplished by technique 2
 In this technique
 We have to maintain a pointer that always point to last node,
 Similar to cur that always point to first node.
 This pointer can be named like tail, end, last etc.
 So these pointers can be used to hold the address of last node of doubly linked list.
 So with the help of that pointer we can directly move in backward direction with the help of pre
pointer part of a node.
Procedure:
While (t! = NULL)
{
Printf (“\n %d”, t ->info);
t = t ->back;
}
 After the execution of this procedure all element will print or processed.
 But last will point to the NULL, so again we have to move last pointer to the last node.
 So here ptr named pointer or any norary pointer can be used to move to backward rather then
last move.
 So after the execution the last till now will point to last node.
PRACTICALLY STRUCTURE OF NODE
struct list
{
int no;
Struct list * next;
Struct list * back;
};
typedef struct list dlist; // dlist ->doubly list
In this implementation two or three pointers may be used.
start = always point to first node of list.
T = performing operation helper pointer
last = always point to last node of list
Note:- various operations on doubly linked list can be performed:
With the help of last pointer
Or with out help of last pointer (memory save)
o Generally for memory saving last is not used.
o But it increase complexity, Reduce readability.
o Last pointer may be used to:
o Decrease complexity
o Increase readability of our procedures.
“Operations With Out Last Pointer”

 Vidhya Institute of Information Technology 


58
Ideal ‘Data Structure’

1. INSERTION
2. DELETIONS
Both procedures are almost similar to the singly one but here in doubly we have to consider or
maintain both next or pre pointer of a node.
First node pre pointer contains NULL, because these are no any previous node it is first one.
Last nodes next pointer contain NULL, because then is no any next node, it is last one.
INSERTION IN DOUBLY LINKED LIST
Node can be inserted three different points in list
1. Insert at first
2. Insert at last
3. Insert at mid
Consider n pointer here, which points to the node which is new and which we want to insert in our linked list.
Structure or Syntax of doubly linked list:
n = (dlist*) malloc (sizeof(dlist));
n ->info = data;
n ->next = NULL;
n ->back = NULL;
Insert at first
Step 1. start.
step 2: create a new node n. void addfront(void)
step 3: check if (start = NULL) then, {
set n->info=data struct node *n=(struct nod*)malloc(sizeof(struct node));
set n->next=NULL. printf(“\n enter the information ”);
set n->back=NULL. scanf(“%d”,&n->info);
set Start = n if(start==NULL)
Step 2. otherwise {
set n->next = start; start=n;
set start->back = n; start->back=NULL;
set start=n; start->next=NULL;
[end of if] }
step 3: stop else
{
n->next=start;
start->back=n;
Description: n->back=NULL;
start=n;
}
}

 Vidhya Institute of Information Technology 


59
Ideal ‘Data Structure’

Insert at last
Step 1: start.
step 2: create a new node n. by malloc and insert the information.
step 3: check if (start = NULL) then,
set n->info=data void addlast(void)
set n->next=NULL. {
set n->back=NULL. struct node *n=(struct node*)malloc(sizeof(struct node));
set Start = n printf(“\n enter the information ”);
Step 4. otherwise scanf(“%d”,&n->info);
repeat step (a) while(t->next!=NULL) if(start==NULL)
step(a) set t:=t->next. {
[end of loop] start=n;
set t->next = n; start->back=NULL;
set n->back = t; start->next=NULL;
set n->next=NULL; }
[end of if] else
step 5: stop {
while(t->next!=NULL)
Description: t=t->next;
Step1: if start is NULL then t->next=n;
 Make n as initial node n->back=t;
n->next=NULL;
 Start & t both point to the n node
}
Step2: otherwise
}
Move t to last node not at its address part
Step3: start ->next = n change
Now start pointing to last node connects this last node with n new node.

With the help of Last pointer :


 It is easy way.
 No need to loop.
 Directly last pointed ending node connect to n

Procedure:
Last ->next = n;
n->back = last;
last =n;

 Vidhya Institute of Information Technology 


60
Ideal ‘Data Structure’

n
n->back=last & last=n

Insert to mid (after the constant)


here t pointer is used to perform swapping of addresses.
data, value of node after which new node will insert
Procedure:
Step 1: check if (start = NULL) then,
set Start := n;
set start->next=start.
set start->back=start.
Step 2: otherwise
repeat step (a) While (t!= NULL),
step (A) check if(t->info:=data) then,
goto step
otherwise
t := t ->next;
(end of if)
[end of loop]
Step 3: check if (t=NULL) then,
print” not found”
goto step 8
[end of if]
Step 4: set n->next := t->next;
Step 5: set t->next ->back := n;
Step 6: set t->next:= n;
Step 7: set n ->back := t;
[end of if]
Step 8: stop.
Description:

 Vidhya Institute of Information Technology 


61
Ideal ‘Data Structure’

“node inserted at mid after constant”


DELETION IN DOUBLY LINKED LIST
Deletion can done at three levels of point.
1. Delete from first
2. Delete from last
3. Delete from mid.
o Doubly linked list deletion is almost similar to the singly linked list.
o But in doubly linked list two addresses will manipulate pre & next so here we have to consider
two addresses for every node.
Delete from front
Procedure:
void delfront(void)
Step 1: set pointer t=start.
{
Step 2: check if (start = NULL) then,
struct node *t=start;
print“ no nodes to delete”
if(start==NULL)
otherwise
printf(“\n linked list is empty”);
Step 3: set start= start->next.
else
Step 4: free (t);
{
Step 5: set start->back=NULL
start=start->next;
[end of if structure]
start->back=NULL;
step 6: stop.
free(t);
printf(“\n node deleted from front”);
}
}

 Vidhya Institute of Information Technology 


62
Ideal ‘Data Structure’

Delete from last


Procedure:
Step 1: check if (start = NULL) then,
Print “ no node to delete”
Step 2: otherwise
repeat step (a) While (t ->next ->next! = NULL) ,
set t = t ->next;
[End of loop]
Step 3: free (t ->next);
Step 4: set t ->next =NULL;
[end of if]
step 5: stop

Delete From Mid

 Node can be deleted easily from mid but we have to takes case of both next & back pointer.
 Node can be deleted by node number or by node value so any one technique is used.
 Generally node after given value technique is used for deletion.
Procedure:
Step 1: if (start = = NULL)
Print “node to delete”
Step 2: otherwise void delmid(void)
repeat step (a) While (t!=NULL), {
step (a) check if(t->info=data) then, int data;
goto step struct node *t=start;
otherwise printf(“\n enter the data you want to delete ”);
Step 3: set t=t->next. scanf(“%d”,&data);
[end of if structure] if (start = = NULL)
printf (“\n list is empty”);
Step 4: check if t=NULL then,
else
print “constant not found”
[end if stucture]
[end of loop]

 Vidhya Institute of Information Technology 


63
Ideal ‘Data Structure’
{
While (t!=NULL)
Step 5: set t->back->next=t->next. {
Step 6: set t->next->back=t->back. if(t->info=data)
step 7: free(t). break;
step 8: stop. else
t=t->next;
}
if (t==NULL)
{
printf( “\n constant not found”);
return;
}
t->back->next=t->next;
t->next->back=t->back;
free(t);
}

 A doubly linked list in circular from is known as doubly circular linked list.
 It is similar to the singly circular linked list but addresses are different here.
 In out doubly linked list previous pointer of first node is NULL , and next pointer of last node
is also NULL.
 We use this pointer to hold addresses rather then NULL value.
Structure:
In doubly circular linked list:
First node pre pointer hold the addresses of last node and last node next pointer hold the addresses of
first node .

 Vidhya Institute of Information Technology 


64
Ideal ‘Data Structure’

DOUBLY CIRCULAR LINKED LIST

Pictorial representation:

General doubly linked list:

Question What is use of cur in doubly circular list ?


Answer Yes, it is genuine question that first node address of last node or last node has addresses of first node then
what is use of cur pointer.
As we known that for performing various operation either insertion or deletion we have to move point
either at start or at last or at mid.
Again there is no problem we have to move to required (first) node again by loop.
So if from any location we want to move on a first node or last node we have to take the help of loop so
again use of loop is “time consuming” process here time complexity increases.
That’s why to solve this problem cur pointer is used because cur is pointing to first node and cur also has
addresses of last node in pre pointer. So with the help of cur pointer with out using loop we can directly
pointing to first or last node.
Consider following lines:
Suppose we want to move ptr to last node, if want to pointing it at start node direct use cur like this :
ptr = t
Suppose we want to move ptr to last node directly we can write:
ptr = t ->back [pre contain address of last node]
loop not used here [time save]
Insertion in Doubly Linked List
Insertion again done at three level / point
1. Insert at first
2. Insert at last
3. Insert at mid
Note keep in mid that first node previous part should always point to last node and last
node addresses part should always point to first node.
 n pointer is used.
 n holds the addresses of new node.
 This n we want to insert in existing list .
 Structure of node
struct node
{
struct node *back;
int info;
struct node *next;
};
Insert at first
Step1: check if (start = NULL) then
set Start = n;
set start->back=start
set start->next=start
Step2: otherwise
Step 3: set n->next=start.
step 4: set start->back=n.
step 5: repeat step (a) while(t->next!=start) then,
step(a) t=t->next;
step 6: set t->next=n and set n->back=t.

 Vidhya Institute of Information Technology 


65
Ideal ‘Data Structure’

step 7: set start=n.


[end of if]
step 8: stop.

void addfront(void)
{
struct node *t=start;
struct node*n=(struct node *)malloc(sizeof(struct node));
printf(“\n enter the information ”);
scanf(“%d”,&n->info);
if(start==NULL) II logic
{ t=start->back;
start=n;
start->next=start;
n->next=t->next;
start->back=start; t->next->back=n;
} t->next=n;
else n->back=t;
{ start=n;
n->next=start;
start->back=n;
while(t->next!=start)
t=t->next;
t->next=n;
n->back=t;
start=n;
}
printf(“\n node inserted at front…..”);
}

 Vidhya Institute of Information Technology 


66
Ideal ‘Data Structure’

EDUCATION MAKES THE IDEAL MAN &


WE PROVIDE THAT EDUCATION

We Provide …
 Specialization in All IT Languages

 C  C++
 DS  DBMS
 VB  Android
 Java  Advance Java
 Struts, Hibernate, Spring  J2ME
 VB.Net  ASP.Net with C#
 PHP  Advance PHP
 Sun Certified Java (SCJP)  Oracle (OCP)
 C++
 DBMSIndustrial Training by VHS2 Pvt. Ltd.
 Android
 Advance Java M.Tech. Subjects Coaching
B.Tech,
 J2MEIndustrial Training by VHS2 Pvt. Ltd.
 BCA,with
ASP.Net MCA C#& All IT Subjects Coaching
 Advance PHP
 MCA Entrance
Oracle (OCP) Course with 100% Selection

Diploma All Subjects Coaching


BCAMCA & All IT Subjects
GATE Preparation by Experts
Coaching

VIDHYA INSTITUTE
3, Durga Nursery Road, Nr. Sukhadia House, Manglam Mall, Udaipur-313001.
 Vidhya Institute of
Ph.: 0294-6451362, Information
9214465362, Technology 
9251420811.
67
Ideal ‘Data Structure’

Insert at last
 In a circle there is no any fast and last point.
 So insertion at last is similar to the insert at first in this technique step 7 will not used.
 Because cur makes node first we don’t move t then 10 nodes always first and 5 ns treat at last because they
are in circle.
 And generally previous node of first node in circle is a last node.

Procedure:
Step1: check if (start = NULL) then
set Start = n;
set start->back=start
set start->next=start
Step2: otherwise
Step 3: set n->next=start.
step 4: set start->back=n.
step 5: repeat step (a) while(t->next!=start) then,
step(a) t=t->next;
step 6: set t->next=n.
step 7: set n->back=t.
[end of if]
step 8: stop.
void addlast(void)
{
struct node *t=start;
struct node*n=(struct node *)malloc(sizeof(struct node));
printf(“\n enter the information ”);
scanf(“%d”,&n->info);
if(start==NULL)
{ II logic
start=n;
start->next=start; t=start->back;
start->back=start; n->next=t->next;
}
else
t->next->back=n;
{ t->next=n;
n->next=start; n->back=t;
start->back=n;
while(t->next!=start)
t=t->next;
t->next=n;
n->back=t;
}
printf(“\n node inserted at front…..”);
}

“Node inserted successfully at last”

 Vidhya Institute of Information Technology 


68
Ideal ‘Data Structure’

 If we see the diagram it is looking like insertion at first but cur is not moved and if we traverse it output
will be 10---20---30 40---5
 It is circular so diagram of this type is possible here n is at last because Previous node of first node in a
circle is last node so n is a last node.
 Now we can represent with the following diagram.

Insert at mid
 Insert at mid is exact similar to as in normal doubly because at mid these is no any concept of linear or
circular.

Deletion in doubly linked list


These points of deletion:
1. Delete from first
2. Delete from last
3. Delete from mid
Delete from first
Here we have transfer the addresses hold by first node to its second node , so last node connect
with second one and free first node and make second as first
Procedure:

void delfront(void) algorithm


{ step 1 : start.
struct node *t=start; step 2: declare struct node *t=start.
if(start==NULL) step 3: check if(start=NULL) THEN,
printf(“\n linked list is empty”); print”empty linked list”
else if(start->next=start) again check if(start->next=start) then,
{ free(t)
free(t); set start=NULL.
start=NULL; otherwise
} step 4: set start=start->next.
else step 5: set t->back->next=t->next;
{ step 6: set t->next->back=t->back;
start=start->next; step 7: declare free(t).
t->back->next=t->next; [end of if]
t->next->back=t->back; step 8: stop.
free(t);
}
printf(“\n node deleted….”);
}

t->next

 Vidhya Institute of Information Technology 


69
Ideal ‘Data Structure’

Delete from last


Here we have transfer the addresses hold by t pointer to its last node , then perform the task same as
previous.

void dellast(void) algorithm


{ step 1 : start.
struct node *t=start; step 2: declare struct node *t=start.
if(start==NULL) step 3: check if(start=NULL) THEN,
printf(“\n linked list is empty”); print”empty linked list”
else if(start->next=start) again check if(start->next=start) then,
{ free(t)
free(t); set start=NULL.
start=NULL; otherwise
} step 4: set t=start->back.
else step 5: set t->back->next=t->next;
{ step 6: set t->next->back=t->back;
t=start->back; step 7: declare free(t).
t->back->next=t->next; [end of if]
t->next->back=t->back; step 8: stop.
free(t);
}
printf(“\n node deleted….”);
}

 Vidhya Institute of Information Technology 


70
Ideal ‘Data Structure’

Delete from mid


Deletion from mid is similar to the deletion of node from mid in linked list of doubly type.
Because in mid there is no any concept of doubly or because circular in mid of first so same procedure is used
for delete in double circular.
Now finally above procedure will remove the node from mid of the list whose values is equal to the solve

SOME POINTS FOR THESE ALL PROCEDURES


 Number of different – different technique can be these for insertion & deletion in linked list.
 Technique can be differ.
 These all above technique are simple and design to reduce the complexity of time space and
program.
 They can be easily understandable.
 According to requirement t or ptr or n pointers are also used with out them.
These all operation can perform but it will become complex,
So these intermediate pointers are used.

STACK USING LINKED LIST


 As we know stack is a linear structure data type
 It can be implemented with the help of either array or linked list.
 Array is a static memory allocation so, it is not preferred.
 Linked is a dynamic memory allocation so it is used for implementing stack generally.
 For implementing stack either singly or doubly linked list can be used.
 Generally singly linked .list is preferred to reduce complexity.
 Stack work on fashion of LIFO [last in first out]
 Here the same fashion LIFO will apply on linked list.
 When performing operation on stack then following approach is used.
 General point is :
Insertion & deletion will done at one point.
PUSH:
This will insert the node at first allocation in list.
POP
This will remove the node from first location in list.
Because this node was inserted last.
For example we PUSH following element

1. When 50 is PUSH (initial node)

2. PUSH 40

3. PUSH 30

4. PUSH 20

5. PUSH 10

 Vidhya Institute of Information Technology 


71
Ideal ‘Data Structure’

When we traverse element:


Output will be

When we pop element:

First pop

Popped element is 10

Second pop t

Popped element is 20

Third pop

Popped element is 30

Fourth pop

Popped element is 40.

Fifth pop

poped element is 50 empty linked list

IMPLEMENTATION OF STACK USING LINKED LIST


#include<stdio.h>
#include<conio.h>
#include<process>
struct list
{
int no;
struct list * next;
};
typedef struct list stack; // name for convening
Void main ()
{
stack * start, * n,*t;
int data;
start = NULL;
while (1)
{
clrscr ();
printf (“\n 1.push”);
printf (“\n 2 pop”);
printf (“\n 3 display”);
printf (“\n \t enters your choice”);
scanf (“%d”, &n);
switch (n)

 Vidhya Institute of Information Technology 


72
Ideal ‘Data Structure’

{
case 1:
n = (stack *) malloc (sizeof (stack));
n ->next = NULL;
printf (“\n enters value to be push”);
scanf (“%d”, & n ->no);
if (start ==NULL)
start=n;
else
{
n ->next = start;
start = n;
}
printf (“\n elements push successfully”);
break;
case 2:
if (start = = NULL)
printf (“\n stack underflow”);
else
{
printf (“\n popped element is %d”, start ->no);
t = start;
start = start ->next;
free (t);
printf (“\n element popped successfully”);
}
break;
case 3:
if (start = = NULL)
{
printf (“\n stack underflow”);
printf (“\n no. element to traverse”);
}
else
{
printf (“\n elements of stack are”);
t = start;
while (t! = NULL)
{
printf (“\n %d”, t ->no);
t = t->next;
}
/* here n is used so start does not move from its actual location*/
/*t is only temprary pointer*/
break;
case 4:
exit (0);
}// closing of switch ()
getch ();
}//closing of infinite while loop
}//closing of main () function

KEY POINTS ABOUT LOGIC UNIT


 For conveniences, stack name is used for structure another name can also be used (you
name also) or any valid modifier.
 For intermediate processing for holding the address pointer is required so n is
 Used n is used in push also and in pop operation will run, so n used for
 Both.
 While (1) infinite loop for continuous display of men until press 4.

 Vidhya Institute of Information Technology 


73
Ideal ‘Data Structure’

QUEUE USING LINKED LIST


 Queue is a linear data structure similar to stack but basic difference is that both work on different –
different fashion or technique.
 Queue can be implemented with the help of either array linked list.
 Because of dynamic memory allocation linked list implementation is preferred.
 Singly or doubly linked list can be used.
 Singly linked list is preferred
 Queue work on fashion of FIFO [first in first out]
 Here equal fashion FIFO applied on linked list.
 As a conclusion we can say.
That insertion & deletion will done on different –different points or an linked list (front rear )
 During performing operation on queue following approach is used.

ENQUEUE(insertion in queue)
This operation will insert the node at last in list
DEQUEUE (deletion in queue)
This operation will remove the node from first in list because if node insert at first then it will
remove from last or
If node is inserted at last then it will remove from first.

IMPLEMENTATION OF QUEUE USING LINKED LIST

#include<stdio.h>
#include <conio.h>
#include<process>
struct list
{
int no;
struct list * next;
};
typedef struct list queue;
void main ()
{
queue * start ,* n, *t;
int n;
t = start = n = NULL;
while (1)
{
clrscr ();
printf (“\n 1. Enqueue”);
printf (“\n 2. display”);
printf (“\n 3. exit”);
printf (“\n \t enters your choice”);
scanf (“%d”, &n);
switch (n)
{
case 1:
t = start;
n = (queue*) malloc (sizeof( queue));
n ->next = NULL;
printf (“\n enters value for enqueue”);
scanf (“%d”, & n ->info);
if (start = = NULL)
start = n;
else
{
while (t ->next! =NULL)

 Vidhya Institute of Information Technology 


74
Ideal ‘Data Structure’

t = t ->next;
t ->next = n;
}
printf (“\n element queue successfully”);
break:
case 2:
t = start;
if (start = =NULL)
printf (“\n queue underflow”);
else
{
printf (“\n dequeue element is %d”, start ->no);
start = start ->next;
free (start);
start = t;
printf (“\n element dequeuesuccesfully”);
}
break;
case 3;
t=start;
if (start = =NULL)
printf (“\n queue underflow”);
else
{
printf (“\n elements of queue are”);
while (start! =NULL)
{
printf (“\n %d”, t ->no);
t = t ->next;
}
}
break;
case 4;
exit (0);
}// closing of switch
getch ();
}// closing of while loop
}//closing of main ()

SOME KEY POINTS ABOUT ABOVE LOGIC


 For convenience queue name is used for structure another valid (modifier) name can be given.
 Two different start & cur pointers are used because two locations are used
 One for insertion (last)
 One for deletion (first)
 So operations performed by start but it is singly back ward movement is not possible so cur is used which
hold the addresses of first node always.
 For deletion cur is moved to next node
 Every case in above program start with start = cur to allocate again start at first node.

Pictorial representation of queue linked list

ENQUEUE 10

ENQUEUE 20

 Vidhya Institute of Information Technology 


75
Ideal ‘Data Structure’

ENQUEUE 30
ENQUEUE 40

ENQUEUE 50

DEQUEUE 10

DEQUEUE 20

DEQUEUE 30

DEQUEUE 40

DEQUEUE 50 EMPTY LIST.

Polynomials Representation

linked list are used to represent and manipulate polynomials.ex.


p(x)=3x5 -2x3+7x+4

poly 2; 8x7-6x5+2x4-2x

after the addition of poly1 & poly2


8x7-3x5+2x4-2x3+5x+4

 Vidhya Institute of Information Technology 


76
Ideal ‘Data Structure’

Step 1: begin.
Step 2: scan the list 1 and list 2 one by one.
Step 3: compare the exponent of the list1 with exponent of the list2
(i) If one node has higher exponent than another node then add the higher
exponent node in the list3 and scan the next node in higher exponent node.
(ii) If the nodes have same exponent value then add the coefficient of both
nodes and add the result in list3 and scan the next nodes in both the lists.
Step 4. Repeat the same process until one list finished.
Step 5. Add the remaining nodes of another unfinished list in list3.
Step 6. Stop.
Polynomials Representation
struct node
{
int coef;
int expo;
struct node *next;
};
struct node *first,*sec,*new;
struct node * create(struct node *start);
void display(struct node *start);
struct node * addpoly(struct node *first,struct node *sec);
void main()
{
int num,I,choice,pos;
first=NULL,sec=NULL,new=NULL;
clrscr();
do()
{
printf(“\n 1. Create first poly”);
printf(“\n 2. display first”);
printf(“\n 3. Create second poly”);
printf(“\n 4. display second”);
printf(“\n 5. add polynomials”);
printf(“\n 6. display”);
printf(“\n 7. exit”);
printf(“\n enter the choice…..”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
first=create(first);
break;
case 2:
display(first);
break;
case 3:
sec=create(sec);
break;
case 4:
display(sec);
break;
case 5:
new=addpoly(first,sec);
break;
case 6:
display(new);

 Vidhya Institute of Information Technology 


77
Ideal ‘Data Structure’

break;
case 7:
exit(0);
default: printf(“\n invalid choice…….”);
}
getch();
}while(1);
}

struct node * create(struct node * start)


{
struct node * n ,*t;
n=(struct node*)malloc(sizeof(struct node));
printf(“\n Enter the coefficient ”);
scanf(“%d”,&n->coef);
printf(“\n Enter the Exponent ”);
scanf(“%d”,&n->expo);
if(start=NULL)
start=n;
else
{
t=start;
while(t->next!=NULL)
t=t->next;
t->next=n;
}
return(start);
}

void display(struct node *t)


{
if(t==NULL)
{
printf(“\n list is empty ”);
return;
}
else
{
printf(“\n Item in list :- \n”);
while(t!=NULL)
{
printf(“+ (%d)x^%d”,t->coef,t->expo);
t=t->next;
}
printf(’’ \n“);
}
}

struct node * addpoly(struct node * first,struct node *sec)


{
struct node *third,*n,*last;
third=NULL;
while(first!=NULL && second !=NULL)
{
n=(struct node *)malloc(sizeof(struct node));
if(first->expo==sec->expo)
{
n->coef=first->coef+sec->coef;
n->expo=first->expo;
first=first->next;

 Vidhya Institute of Information Technology 


78
Ideal ‘Data Structure’

sec=sec->next;
}
else if(first->expo> sec->expo)
{
n->coef=first->coef;
n->expo=first->expo;
first=first->next;
}
else
{
n->coef=sec->coef;
n->expo=sec->expo;
sec=sec->next;
}
n->next=NULL;
if(third==NULL)
{
third=n;
last=n
}
else
{
last->next=n;
last=n;
}
}
while(first!=NULL)
{
n=(struct node *)malloc(sizeof(struct node));
n->coef=first->coef;
n->expo=first->expo;
n->next=NULL;
}
if(third==NULL)
{
third=n;
last=n
}
else
{
last->next=n;
last=n;
}
}

while(sec!=NULL)
{
n=(struct node *)malloc(sizeof(struct node));
n->coef=sec->coef;
n->expo=sec->expo;
n->next=NULL;
}
if(third==NULL)
{
third=n;
last=n
}
else
{
last->next=n;
last=n;
}

 Vidhya Institute of Information Technology 


79
Ideal ‘Data Structure’

}
return(third);
}
Header Linked List
A header linked list always contains a special node, called the header node, at the beginning of the list. there are
following two kinds of widely used header lists…
1. A grounded list
It is a header list where the last node contains NULL pointer.

START
header node

2. A Circular header list


it is a header list where the last node points back to the header node.

START
header node

Application / Use of Linked list


There are variety of areas where linked list is used.
 Linked list is based on Dynamic memory Allocation that’s why it is always preferable because if
reduce memory complexity.
 Linked list applications are wide some of them measure are:
Most Important Application
Most valuable application is that
 “It Is Used In Implement Another Data Structures”
 Tree, graph, Heap, stack, Queue, these all data structure are implemented with the help of
Linked list
 Without linked list tree or graph type structures can not be implemented very easily.
 For there effective and efficient representation Linked list always used.
 Used is various file organization of our system.
 Used in collision or resolution Technique in hashing.
 [Chaining Method]
 To represent SPARSE Matrix.
 To maintain any list of items of many be different types.
 To perform arithmetic operation on long integers.
[Long integers maintain in different Blocks or node of list]
 Also used for where storage requirement is Unknown.
 Used where Dynamic memory allocation concept is used.
 Used where contiguous memory not available such as sorting a blocks of a file in random order
on a disk if contiguous space is not available.

Representation of Polynomials:-
As we say that linked list is used to manipulate polynomials, manipulation refers to addition, subtraction
Or multiplication of polynomials
 First of all how a polynomial represented using Linked list:
 Any polynomial Contain:
 Coefficient of base (x)

 Vidhya Institute of Information Technology 


80
Ideal ‘Data Structure’

 Power of base (x)


 This may be multiple (x,y,z)
 According to this structure of node is defined

Suppose Polynomial is

5x 3 5 + 9x 2 - 7x +2
Here only x is used so structure of node:

Coefficient of x Power of x Link to next


If two base x & y is used, then structure of node is:

Coefficient of x Power of x Power of y Next


Representation of following polynomials

5x3 +9x2-7x+2

5 3 9 2 -7 1 2 0 x

Representation of following Polynomial:

4x 3 y 2 +9x 2 +1 0x y - 3x +7

4 x 3 y2 9 x2 y 10 x1 y1 -3 x1 y0
7 x0 y0
4 3 2 9 2 1 10 1 1 -3 1 0 7 0 0
x
X Coeff.  In this Way any type of polynomials can be represented easily.
 The Structure of node will depend on polynomials.
Power of x.
 So first, it must decide then it should implement.

Power of y

To perform Addition Consider follow steps:-


1. Read every node of list on by one.
2. Power which occurs only one time in polynomial is directly copied into new result polynomial the
coefficient of base with same power are added and then new from copied into result polynomial.

In this way operations perform on polynomials.


3. Structure can also be used, but No. of terms are not fixed that’s way size is unknown so dynamically
nodes are allocated in Linked list.

Some Questions
Q. 1 What is link list ? What are the advantages of link list over array ?
Q. 2 Write an algorithm to create a single linked list ?
Q. 3 Write a C program to create a singly linked list of records sorted in ascending order.
Q. 4 Suppose the names of few students of a class are as below : Pankaj, Manoj, Sohan, Ram, Payal. It is
assumed that the names of students are represented as singly linked list.
(A) Write a C Function to reach whether the name Payal is present or not.
(B)Write an algorithm to delete the name Sohan.
Q. 5 What are the various operators possible in a singly linked list ? Explain all of them with algorithm.
Q. 6 Write a C program to delete a node containing a give information in a doubly linked list.
Q. 7 Write a algorithm to insert a sorted singly linked list so that the resultant list would also be sorted.

 Vidhya Institute of Information Technology 


81
Ideal ‘Data Structure’

Q. 8 Write an algorithm to remove a node in a singly linked list.


Q. 9 Write a menu drive program to perform the following operations in a doubly linked list:-
(A) create a linked list
(B) Show the list
(C) Count the number of list
(D) Add a node at beginning
(E) Add a node after specified position
(F) Delete a node
Q.10 Write a short node to dynamic memory allocation. How memory is allocated using dynamic memory
allocation function ?
Q.11 Write a program to reads the name, age and salary of 10 person as maintains them in a linked list sorted by
name.
Q.12 Create a linked list to represent the following polynomials :-
3x5+4x4+6x2 -5
15x6+8x4+7x3+2x2+x
Write a function add() to add these polynomials and print the resultant linked list.
Q.13 Write a procedure to traverse a circularly linked lists.
Q.14 Write a procedure to delete a node from a circularly linked lists.
Q.15 A doubly linked list can be made circular by relating the values of links in the first and last nodes
appropriately. Discuss the advantages and disadvantages of circular doubly linked list doing the various list
operations.
Q.16 (A) Define the doubly linked list and circular doubly liked list. Write an algorithm to
create a circular linked list. Also give the structure of a NODE for these list.
(B) Write an algorithm to perform the following operations in a doubly linked list :
(I) To insert a node at the end
(II) To delete a specified node
Q.17 Write a menu driven C program to demonstrate the following operations of a doubly linked list :
(1) To create link list
(2) To insert at the END of the link list
(3) To delete at the beginning of the link list.
(4) To change the information of node.
(5) Display all node of list.

Q.18 Write an algorithm to perform each of the following operations on singly link list :
(1) Add an element to the end of a list.
(2) Concatenate two lists.
(3) Delete the nth element from a list.
(4) Mack a second copy of a list.
Q.19 What is the difference between Static and Dynamic data structure. Give their merits and demerits. Explain
with suitable example of both.
Q,20 Write an algorithm to insert an element into a single link list.
Q.21 Write an algorithm to count the total no. of nods in Circular linked list.
Q.22 Write short notes on followings :
(A) Header linked list
(B) Implementation of linked list in memory
Q.23 Write the difference between array and linked list. Also explain the applications of linked list.
Q.24 Write an algorithm to reverse a given linked list.
Q.25 What do you mean by sparse matrices ? Explain the different ways to represent sparse matrices in memory
allocation by giving example.
Q.26 What are the advantages and disadvantages of representing queue as a linked list rather then an array ?

 Vidhya Institute of Information Technology 


82
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


83
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


84
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


85
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


86
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


87
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


88
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


89
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


90
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


91
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


92
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


93
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


94
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


95
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


96
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


97
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


98
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


99
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


100
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


101
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


102
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


103
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


104
Ideal ‘Data Structure’

X X X X

 Vidhya Institute of Information Technology 


105
Ideal ‘Data Structure’

Program for create binary search tree

#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>
struct node
{
struct node *left;
int info;
struct node *right;
};
struct node *root=NULL;
struct node* insert(struct node *root,int data);

 Vidhya Institute of Information Technology 


106
Ideal ‘Data Structure’

void inorder(struct node *root);


void preorder(struct node *root);
void postorder(struct node *root);
void del(int);
void main()
{
int ch,data;
while(1)
{
clrscr();
printf("\n 1. insert ");
printf("\n 2. inorder");
printf("\n 3. preorder");
printf("\n 4. postorder");
printf("\n 5. delete");
printf("\n 6. exit");
printf("\n enter the choice....");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n enter the data ");
scanf("%d",&data);
root=insert(root,data);
break;

case 2:
if(root==NULL)
printf("\n underflow");
else
inorder(root);
break;

case 3:
if(root==NULL)
printf("\n underflow");
else
preorder(root);
break;
case 4:
if(root==NULL)
printf("\n underflow");
else
postorder(root);
break;

case 5:
printf("\nEnter the data you want to delete ");
scanf("%d",&data);
del(data);
break;

case 6: exit(0);
}
getch();
}
}

struct node* insert(struct node *root, int data)


{
if(root==NULL)

 Vidhya Institute of Information Technology 


107
Ideal ‘Data Structure’

{
root=(struct node*)malloc(sizeof(struct node));
root->info=data;
root->left=NULL; ALGORITHM
root->right=NULL; STEP 1 : START.
} Step 2: check if root= NULL then,
else Assign memory to root block and
{ Set root->info:=data.
if(data<root->info) Set root->left=NULL
root->left=insert(root->left,data); Set root ->right=NULL
else Otherwise
root->right=insert(root->right,data); Step 3: check if (data<root->info) then,
} Call root->left=insert(root->left,data)
return(root); Otherwise
} Call root->right=insert(root->right,data)
( (End of if)
Step 4 stop.
void inorder(struct node *root)
{
if(root!=NULL) Step 1: function inorder(root)
{ Step 2: check if (root!=NULL) then,
inorder(root->left); Call inorder(root-.left);
printf(" %d",root->info); Print root->info
inorder(root->right); Call inorder root-.right.
} [end of if]
} Step 3: Stop.

void preorder(struct node *root)


Step 1: function preorder(root)
{
Step 2: check if (root!=NULL) then,
if(root!=NULL)
Print root->info
{
Call preorder(root-.left);
printf(" %d",root->info);
Call preorder root-.right.
preorder(root->left);
[end of if]
preorder(root->right);
} Step 3: Stop.
}
Step 1: function postorder(root)
void postorder(struct node *root) Step 2: check if (root!=NULL) then,
{ Call postorder(root-.left);
if(root!=NULL) Call postorder root-.right.
{ Print root->info
postorder(root->left); [end of if]
postorder(root->right); Step 3: Stop.
printf(" %d",root->info);
}
}

void del(int data)


{
struct node *t=root,*ptr,*temp;
int save;
if(root!=NULL)
printf("\n Empty tree");
else if(root->info==data)
{
if(root->right!=NULL && root->left==NULL)
{
root=t->right;
free(t);

 Vidhya Institute of Information Technology 


108
Ideal ‘Data Structure’

}
else if(root->right==NULL && root->left!=NULL)
{
root=t->left;
free(t);
} Step 1: start.
else if(root->right==NULL && root->left==NULL) Step 2: check if root!=NULL then,
{ Print “empty tree.”.
free(t); Step 3: check if root->info=data then,
Step (a): check if(root->right!=NULL
root=NULL;
AND root->left=NULL) then,
} Set root=t->right.
} Set free(t).
else Step (b):again check if(root->right=NULL
{ AND root->left!=NULL) then,
while(t->info!=data && t!=NULL) Set root=t->left.
{ Set free(t)
ptr=t; Step (c):again check if(root->right=NULL
if(data<t->info) AND root->left=NULL) then,
Set root=NULL.
t=t->left;
Set free(t)
else Otherwise
t=t->right; Step 4 : repeat step(5,6) while(t->info!=data AND
} t!=NULL)
if(t==NULL) Step 5: set ptr:=t.
{ Step 6: check if data<t->info then,
printf("\n data not found...."); Set t:=t->left.
return; Else
} Set t:=t->right.
[end of if]
if(t->left==NULL && t->right==NULL)
[end of loop]
{ Step 7: check if t=NULL then,
if(data <t->info) Print”data not found”.
ptr->left=NULL; Return.
else Step 8: check if(t->left=NULL AND t->right=NULL) then,
ptr->right=NULL; Step 9 check if data<t->info then
free(t); Set ptr->left:=NULL.
} Else
else if(t->left==NULL && t->right!=NULL) Set ptr->right=NULL.
[End of if]
{
Free node t.
if(data <t->info) Step 10: check if(t->left=NULL AND t->right!=NULL) then,
ptr->left=t->right; Step 11:check if data<t->info then
else Set ptr->left:=t->right.
ptr->right=t->right; Else
free(t); Set ptr->right=t->right.
} [End of if]
else if(t->left!=NULL && t->right==NULL) Free node t.
{ Step 12: check if(t->left!=NULL AND t->right==NULL) then,
Step 13:check if data<t->info then
if(data <t->info)
Set ptr->left:= t-> left
ptr->left=t->left; Else
else Set ptr->right= t-> left
ptr->right=t->left; [End of if]
free(t); Free node t.
} Step 14: check if(t->left!=NULL AND t->right!=NULL) then,
else if(t->left!=NULL && t->right!=NULL) Set temp:= t->right
{ Repeat step(a) while(temp->left!=NULL),
temp=t->right; Step (a) set temp:=temp->left.
[end of loop]
while(temp->left!=NULL)
Set save:=temp->info.
temp=temp->left; Call del(temp->info).
save=temp->info; Set t->info:=save.
del(temp->info); [End of if]
t->info=save;
}
}
}
 Vidhya Institute of Information Technology 
109
Ideal ‘Data Structure’

Without Recursion
void add(void)
{
int data;
struct node *t=root,*ptr;
struct node *n=(struct node*)malloc(sizeof(struct node));
printf("\n Enter the information ");
scanf("%d",&data);
n->left=NULL;
n->right=NULL; Step 1: start.
n->info=data; Step 2: set struct node *t=root.
if(root==NULL) Step 3: create a new node n and read information in data..
{ Step 4: set n->left=NULL, n->right=NULL,n->info=data
root=n; Step 5: check if (root= NULL) then,
} Set root:=n.
else Otherwise
{ Repeat step while(t!=NULL AND t->info!=data)
while(t!=NULL && t->info!=data) Set ptr:=t.
{ Check if data<t->info then,
ptr=t; Set t:=t->left.
if(data<t->info) Otherwise
t=t->left; Set t:=t->right.
else [end of if ]
t=t->right; [end of loop]
} Step 6: check if t->info=data then,
if(t->info==data) Print “already present”
{ return
printf("\n already present "); End if
return; Step 7: check if (data < ptr-> info) then,
} Set ptr->left=n.
if(data<ptr->info) Otherwise
ptr->left=n; Set ptr->right=n.
else End if
ptr->right=n; Step 8: stop.
printf("\n node inserted.....");
}
}

Binary Tree Creation


struct node* insert(struct node *root, int data)
{ ALGORITHM
if(root==NULL) STEP 1 : START.
{ Step 2: check if root= NULL then,
root=(struct node*)malloc(sizeof(struct node)); Assign memory to root block and
Set root->info:=data.
root->info=data;
Set root->left=NULL
root->left=NULL; Set root ->right=NULL
root->right=NULL; Set count:= count+1.
count++; Otherwise
} Step 3: check if (count mod 2 = 0) then,
else Call root->left=insert(root->left,data)
{ Otherwise
if(count%2==0) Call root->right=insert(root->right,data)
root->left=insert(root->left,data); ( (End of if)
Step 4 stop.
else
root->right=insert(root->right,data);
}
return(root); }

 Vidhya Institute of Information Technology 


110
Ideal ‘Data Structure’

PROGRAM FOR DIFFERENT-DIFFERENT OPERATIONS


#include<stdio.h>
#include<conio.h>
#include<process.h>

struct tree
{
int no;
struct tree *left;
struct tree *right;
};
typedef struct tree stree;
stree * insert (stree *root,int n);
void inorder(stree *root);
void preorder(stree *root);
void postorder(stree *root);
void mirror(stree *root);
int height(stree*);
int enode(stree*);
int inode(stree*);
int total(stree*);
stree* min(stree*);
stree* max(stree*);
void main()
{
int t;
stree *root=NULL,*temp;
int n;
while(1)
{
clrscr();
printf("\n1. Insert Node");
printf("\n2. Inorder");
printf("\n3. Preorder");
printf("\n4. Postorder");
printf("\n5. Total Nodes");
printf("\n6. External Node");
printf("\n7. Internal Node");
printf("\n8. Height");
printf("\n9. Minimum");
printf("\n10. Maximum");
printf("\n11. Mirror");
printf("\n12. Exit");
printf("\n\n\t\t\tEnter Your Choice.....");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\nEnter Value For Insertion : ");
scanf("%d",&n);
root=insert(root,n);
printf("\nNode Inserted Successfully");
break;
case 2:
if(root==NULL)
printf("\nTree Is Empty");
else
{
printf("\nInorder Traversal Of Tree Is \n");
inorder(root);
}

 Vidhya Institute of Information Technology 


111
Ideal ‘Data Structure’

break;
case 3:
if(root==NULL)
printf("\nTree Is Empty");
else
{
printf("\nPreorder Traversal Of Tree Is \n");
preorder(root);
}
break;
case 4:
if(root==NULL)
printf("\nTree Is Empty");
else
{
printf("\nPostorder Traversal Of Tree Is \n");
postorder(root);
}
break;
case 5:
if(root==NULL)
printf("\nTree Is Empty");
else
{
t=total(root);
printf("\nTotal Nodes in Tree Is %d",t);
}
break;
case 6:
if(root==NULL)
printf("\nTree Is Empty");
else
{
t=enode(root);
printf("\nTotal External Nodes are %d",t);
}
break;
case 7:
if(root==NULL)
printf("\nTree Is Empty");
else
{
t=total(root)-enode(root);
printf("\nTotal Internal Nodes are %d",t);
}
break;
case 8:
if(root==NULL)
printf("\nTree Is Empty");
else
printf("\nHeight of Tree Is %d",height(root));
break;
case 10:
if(root==NULL)
printf("\nTree Is Empty");
else
{
temp=max(root);
printf("\nMaximum Value of tree Is : %d",temp->no);
}
break;

 Vidhya Institute of Information Technology 


112
Ideal ‘Data Structure’

case 9:
if(root==NULL)
printf("\nTree Is Empty");
else
{
temp=min(root);
printf("\nMinimum Value of tree Is : %d",temp->no);
}
break;
case 11:
if(root==NULL)
printf("\nTree Is Empty");
else
{
mirror(root);
printf("\nTree has Mirror");
}
break;
case 12:
exit(0);
}
getch();
}
}
void inorder(stree *root)
{
if(root!=NULL)
{
inorder(root->left);
printf("\n%d",root->no);
inorder(root->right);
}
}
void preorder(stree *root)
{
if(root!=NULL)
{
printf("\n%d",root->no);
preorder(root->left);
preorder(root->right);
}
}
void postorder(stree *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("\n%d",root->no);
}
}
void mirror(stree *root)
{
stree *temp;
if(root!=NULL)
{
mirror(root->left);
mirror(root->right);
temp=root->left;
root->left=root->right;
root->right=temp;
}

 Vidhya Institute of Information Technology 


113
Ideal ‘Data Structure’

}
int height(stree *root)
{
int lh,rh;
if(root==NULL)
return 0;
else
{
lh=height(root->left);
rh=height(root->right);
if(lh>rh)
return ++lh;
else
return ++rh;
}
}
int total(stree *root)
{
if(root==NULL)
return 0;
else
return total(root->left)+total(root->right)+1;
}
int enode(stree *root)
{
if(root==NULL)
return 0;
else if(root->left==NULL && root->right==NULL)
return 1;
else
return enode(root->left)+enode(root->right);
}
int inode(stree *root)
{
return 0;
}
stree* max(stree *root)
{
if(root==NULL || root->right==NULL)
return root;
else
max(root->right);
}
stree* min(stree *root)
{
if(root==NULL || root->left==NULL)
return root;
else
max(root->left);
}
Stree* insert (stree *root,int n)
{
if( (root)==NULL)
{
(root)=(stree*)malloc(sizeof(stree));
(root)->no=n;
(root)->left=(root)->right=NULL;
}
else if( (root)->no > n)
insert( root->left,n);
else
insert( root->right,n); }

 Vidhya Institute of Information Technology 


114
Ideal ‘Data Structure’

HEIGHTLY BALANCED TREE

 Vidhya Institute of Information Technology 


115
Ideal ‘Data Structure’

AVL TREE

 Vidhya Institute of Information Technology 


116
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


117
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


118
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


119
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


120
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


121
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


122
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


123
Ideal ‘Data Structure’

GENERAL TREE

 Vidhya Institute of Information Technology 


124
Ideal ‘Data Structure’

B-TREE

 Vidhya Institute of Information Technology 


125
Ideal ‘Data Structure’

B-TREE

 Vidhya Institute of Information Technology 


126
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


127
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


128
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


129
Ideal ‘Data Structure’

Deletion from B-Tree

 Vidhya Institute of Information Technology 


130
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


131
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


132
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


133
Ideal ‘Data Structure’

Tries

 Vidhya Institute of Information Technology 


134
Ideal ‘Data Structure’

B+- TREE

 Vidhya Institute of Information Technology 


135
Ideal ‘Data Structure’

GRAPH
 graph is a non-linear data structure.
 A random structure.
 No any fixed structure.
 Non hierarchical data structure.
 Basically used to represent relationship between or among pair of elements.

Definition
 Graph G is a set (V, E) where V represent set of elements called “Vertices” and E represent edges
between these vertices.
 Graph is a collection of connected nodes in any order called Vertices and there vertices connected by
Edges.
So G= (V, E)

V = Vertices E = Edges (v, u)

V = {v1, v2, v3, v4-----------} E = {e1, e2, e3, e4, ----------}

Example of graph:-
1. 2.
e1 V1
V1 V2
e1 e2
e5 e6

e4 e2 e4 e5
V5
e7 e8
V2 V3
V3 e3 V4
e3

Details of Graph 1.

G = (V, E)
V = {V1, V2, V3, V4, V5,}
E = {e1, e2, e3, e4, e5, e6, e7, e8}

Where Initial vertex terminal vertex

e1 = (v1, v2) e2 = (v2, v4) e3 = (v3, v4)


e4 = (v3, v1) e5= (v1, v5) e6 = (v2, v5)
e7 = (v5, v3) e8 (v5, v4)

Graph Terminology
Vertex: - Node of Graph (G), represented by V.

Edge: - Node connecting lines, represented by E.

Adjacent Vertices: - Edge connecting vertices called


 Adjacent vertices.
 Also known as Neighbours.
 Also called Endpoints.
e1 = (v1, v2)

Adjacent node

 Vidhya Institute of Information Technology 


136
Ideal ‘Data Structure’

Degree of Vertex deg (v)


Degree of vertex is the number of edges it contain, represent by deg (v).
Degree of vertex is the total number of incoming and out going edges.

Indegree of vertex indeg (v)


Indegree of vertex refers to total number of only incoming edges of any vertex.

Outdegree of vertex outdeg (v)


Outdegree of vertex refers to total number of only outgoing edges of any vertex.
Degree of Vertex = (Indegree +Outdegree) of vertex

Isolated vertex
A vertex which is not belongs to any edge is known as Isolated Vertex.
Isolated vertex is not connected in a graph.
deg (isolated vertex) = 0 (always)
Source
A source is a special type of vertex of a graph, which has only outgoing edges, no any
incoming edges.
Means
v is a source if 2
indeg (v) = 0
outdeg (v) > 0

Sink
It is also a special type of vertex of a graph, which has only indegree or incoming edges;
it has no any outgoing edges.
Means
v is a sink.
if outdeg (v) = 0
indeg (v) >0

Parallel Edges
Any two distinct edges e1 and e2 are called parallel edges if they connect equal
neighbours or Adjacent Nodes.
Means
e1 and e2 are parallel edges.
if e1 = (A, B)
e2 = (A, B)
e1 and e2 both have same vertices A & B as an Adjacent Vertex.

Path
Path refers to way or route between any two vertex if it exists.
“Path may be directed or undirected”

Directed Path
If any one edge exist between any two vertex.
Undirected path
If more than one edge exists between any two vertex.

Reachability
A vertex v is said to be reachable from u if there exists a path from vertex u to vertex v.
Cycle
A cycle is a closed simple path between any two vertex.
Number of vertex within any path is known as length of a path.
So a cycle is a closed simple path with length 2 or more. A cycle of length k is known as
k-cycle.
Weight
When any non negative value assigned to the edge, it is called Weight of Edge.
Weight also represent the cost of moving between two vertex or distance between two
vertex.

 Vidhya Institute of Information Technology 


137
Ideal ‘Data Structure’

Types of graph
Several types of graph are here, they are divided in categories because of their structure or organization of vertex in
a graph.

Directed Graph

When an edge in a graph has a specific direction, is known e2


V1 V2
as directed graph. It is also called “Diagraph” When
traversal direction is given in edge is referred as directed e6 e3
graph.Here there is a path between V2 to V1 or V1 to e8
V4.Not V1 to V2 or V4 to V1. In a directed graph only e1 e7 V5
one side can be traversed between two vertex.Means if e
(v, u) is exits then Without specification or direction (edge) e4
e (u, v) does not exist.
V3 V4
e5
Undirected Graph

A graph whose edges are not directed is called as an undirected. e2


Means in any direction two vertexes can be traversed. V1 V2

e6 e3
e8
e1 e7 V5

e4
V3 V4
e5
Weighted Graph

A graph which has all edges as weighted edges is known as A 4 5 C


weighted graph. Means when all edges have assigned a
numerical non negative value in a graph is known as 7 2 B
1
weighted graph Weighted does not depend on structure or
size of edges, because graphically size cannot be identified on
paper. F 3 D

8 E 9
Mixed Graph
e2
A B
A graph which have some edges are directed and some are e3
e1
undirected is called mixed graph, means when a graph is
directed also and undirected also is referred as mixed graph.
e1, e2, e3, e4, e5 are directed edges. C e6 e7 D
e6, e7 are undirected edges.
= “Mixed Graph”
e5 e4
E

Loop Graph
e5
Multiple edges can be there for creating loop for same vertex.
Also called Circular Graph. e1
A loop graph is a graph which has an edge whose adjacent vertex A B
are identical or same. A loop graph is a graph which has at least
one edge whose source and destination vertex are equal.Means e1 e4 e2
= (v, u) e2 = (u, u)
A graph which contains such type of edges is called loop graph.
Example: C D
e1 =(A, B), e2 = (B, D), e3 = (D, C), e4 = (A,C) e3 e6
e5 = (A, A) e6 = (D,D) }
These edges are called “slink”
“loop graph edges”
 Vidhya Institute of Information Technology 
138
Ideal ‘Data Structure’

NULL graph

A graph which has all vertex as isolated vertex is called


NULL graph.An isolated vertex is a vertex,
Which has no edges?
Which is not connected to graph?
When all vertexes are isolated, then this type of graph is
called NULL graph.
Eg of null graph:
All vertices are isolated vertex
.
Multi Graph

e1
When a graph contains parallel edges, is called Multigraph. A E
Means, when in a graph, two or more than two edges are used to e5
join two vertices is called Parallel Edges and graph is called e4 e2 B e3 e6 e7
Multigraph.
C e8 F
e9 e1
D 1
GRAPH REPRESENTATION e1
Graph can be represented in memory in two forms, according to requirement as convenience
0 it can be used.
1 SEQUENTIAL REPRESENTATION
2 LINKED LIST REPRESENTATION

SEQUENTIAL REPRESENTATION
Sequentially graph can be represented in two ways:
 Adjacency matrix
 Incidency matrix
This representation use concept of array means array is used to represent the graph.

Adjacency Matrix Representation


This concept use 2-D array (matrix)
This representation represents relationship among vertices of graph.
That either edge exist between any two vertices or not.
If edges exist, represent by 1
If edges not exist represent by 0
It is indicated by symbol A

So Aij = {1 if v1 and vj are adjacent vertex (edge)}


{0 if v1 and vj not adjacent (no edges)}

This type of matrix contains only either 0 or 1. So these are known as BIT matrix or BOOLEAN matrix.
Adjacency matrix does not consider the order or organization of vertex in a graph.
So any type of order of vertex can be used in matrix but every order result different - different types of matrix.
If (G) graph is undirected then the adjacency matrix of G will Symmetric [Aij = Aji]

Consider the following graph


Adjacency Matrix of graph is: Directed graph

e1
A B
e5 e6

Un- Directed graph E e8 e2


e7
e4
C D
e3

 Vidhya Institute of Information Technology 


139
Ideal ‘Data Structure’

Adjacency Matrix of graph is: un-Directed graph

is a symmetric matrix.

INCEDENCE MATRIX REPRESENTATION

o This concept use 2 d array (matrix)


o This representation represents relationship among vertices and edges of graph.
o That either vertex is adjacent vertex of edge or not.

e1
A B
e6
e5

E e8 e2
e7
e4
C D
e3

Linked List Representation


 By linked list graph can be represented in two different ways :
 Adjacency list representation.
 Multilist representations.
 This both representation use linked list to represent the graph.
 According to requirement singly or doubly linked list is used.

Adjacency list representation


o First of all an array of pointers of list type is created.
o Here the size of array is total no of vertex of graph.
o Type of pointers depends on list of adjacency vertex which is common for all generally (list type).
o Here every block of pointer hold the address of first node of its adjacent nodes linked list.
o This hold address linked list contains the out degree of considered node if it is directed.
o This type of linked list will maintain for every node or vertex and the address of first node of this
linked list will maintain in array of pointer.
o So here we can divide this structure in two parts.
 Array of pointers
 Linked list of adjacent nodes.
Array of pointers
 Here every block of array represents a vertex u of graph.
 This node holds the linked list of adjacent vertex of u.
 So size of array depends on total no of vertex of a graph.

 Vidhya Institute of Information Technology 


140
Ideal ‘Data Structure’

Linked list of adjacent nodes


 Here no of list are maintained.
 These linked lists hold the adjacent nodes of u.
 These linked list first node address hold by about array of pointers.
 Every node of this linked list contains two parts.
 Part 1: [data part] hold value of vertex
 Part 2: [address part] address of next adjacent node if not available then NULL
 If graph is weighted then another part 3 can also be used which is also a data part which hold weight of edge
 part 3: [data part] hold the weight of vertex, which is in its part 1.
For Example

10 20

30

40 50

60

Adjacency list representation of above directed graph:

10 20 40 50 x

20 10 40 50 30 x

30 20 50 x

40 10 60 20 x

50 10 20 30 60 x

60 40 50 x

Generally this list can also be represented like this:


10 20, 40, 50
20 10, 40, 50, 30 10 20
30 20, 50
40 10, 60
50 10, 20, 30, 60 30
60 40, 50
40 50

60

 Vidhya Institute of Information Technology 


141
Ideal ‘Data Structure’

Adjacency list Representation of above Directed Graph:


Here one of those vertices will be include in linked list which are outdegree of any vertex.
For eg > 10->20, 50 not 40 (because it is indegree)

10 20 50 x

30 50 x
20

50 x
30

60 10 20 x
40

60 x
50
X
60

60 has NULL, because it has no outdegree.


In general form this linked list can also represent like this:
10 20, 50
20 30, 50
30 50
40 60, 10, 20
50 60
60 x

To make it completely as dynamic, then array will not be used.


At the place of array, doubly linked list will be used where node contain three data part.
Part 1 : [Address part] [Pre]:
Address of next node of doubly list.
Part 2 : [Data part] [no]
Value of vertex, whose out degree will maintain within further pointed linked list.
Part 3 : [Address part] [next]
Address of first node of linked list of out degree of vertex of data part.
Representation of following undirected graph using Doubly Linked List:
10 20

30

40 50

Representation: 60

10 20 40 50 x

20 10 40 50 30 x

30 20 50 x

40 10 60 20 x

50 10 20 30 60 x

X 60 40 50 x
0

 Vidhya Institute of Information Technology 


142
Ideal ‘Data Structure’

Above representation is better than as before because above one is dynamic, if number of nodes increases
then array cannot expand but in linked list representation a new node can easily be inserted for a vertex.

Representation Of following undirected weighted graph by Doubly Link list

4 Structure of linked list node:


10 20
3
7 6
9 2 30

2
40 50
Value of Weight Link to
7 5 Vertex [Data Part] next vertex
60 [Data Part] [Address Part]

Representation

1 20 4 40 9 50 7
0 x
2 10 4 40 6 50 2 30 3
0 x
3 20 3 50 2
0 x
4 10 9 60 7 20 6
0 x
5 10 7 20 2 30 2 60 5
0 x
X 6 40 7 50 5
0 x
Practically implemented structure of above list:
Two structures are required for:
Doubly Singly
struct dlist struct slist
{ {
int no; int no;
struct dlist * next list; int weight;
struct dlist * next vertex; struct list * next;
}; };

Representation of following directed weighted graph by Link list:

5 A
4 3 5

B 1 6 C
7 2 4
9
D 4 4
E F G
3
3

7
6

 Vidhya Institute of Information Technology 


143
Ideal ‘Data Structure’

Representation:- (Same as before only outdegree will be used)

A C 3 E 1 F 6
x
B D 7 A 4 B 5
X
C G 4 C 5
x
D H 6 E 4
X
E F 3
X
F E 3 C 9
X
G H 7 F 4
x
X H E 3 F 3
x
In form of general list:-
A C, E, F
B D, A, B
C G, C
E F
F E, C
G H, F
H E, F
(Weight may be considered in brackets with outdegree)

Representation of following directed graph with use of Array:

5 A
4 3 5
A C 3 E 2 F 6 x B 6 C
1
7 2 4
9
B D 7 A 4 B 5
D 4 F 4
X E G
3
C G 4 C 5 x 3
7
6
D H 6 E 4
X H
E F 3
X General List with Weight
F E 3 C 9
X A C(3), E(2), F(6)
B D(7), A(4), B(5)
G H 7 F 4 x C G(4), C(5)
E F(3)
H E 3 F 3 x F E(3), C(9)
G H(7), F(4)
H E(2), F(3)

 Vidhya Institute of Information Technology 


144
Ideal ‘Data Structure’

Multi List Representation of any Graph


 This representation is almost similar to the adjacency list representation.
 One difference is here.
Here linked list node structure is different.
Node structure contains three parts.
 Part 1: Hold vertex value [data part]
 Part 2: [Address part]
Hold address of next vertex (out degree)
 Part 3: [weight part]
Hold weight of an edge, if exist
Here in multilist representation only [part 1] is changed.
Part [address part]
 It holds the address of vertex whose value we want to store.
 Means rather than store the value of vertex the address of vertex is used.
 This address is of vertex which is available in doubly linked list.
 Some time according to requirement this type of representation is preferred such as when vertex value is
unknown but vertex exist and generally adjacency list representation is used.

Multilist Representation of following graph:

e9
A
e1 e2

B C
e3 e4 e5
e6

D E
e7 e8 F

e10

Representation

A X

B X

C X

D X

E X

X F X

 Vidhya Institute of Information Technology 


145
Ideal ‘Data Structure’

Graph Traversals
 There are two types of traversals.
 BFS [Breadth First Search]
 DFS [Depth First Search]
 Basically these are searching technique not traversal.
 In graph there is no any main node.
 We have to consider any node as a source node.
 So with the help of this source node remaining nodes are traversed.
 And it is not always possible that all nodes are approachable by source vertex.
 For any type of traversals either stack or queue structures are required.
 For performing traversals on graph, three different status of vertex used which define various condition of a
vertex during traversals.

Status 1: [Ready State]


 Initial state of vertex
Status 2: [Waiting State]
 Vertex waiting to be processed
Status 3: [Processed State]
 Vertex has been processed.
BFS [Breath First Search]
 Queue structure is used.
 Justify starting node A.
 Find out all the neighbors of A.
 Then again find out all the neighbours of the neighbours of A.
 For hold these adjacent or outdegree, queue is used.
 When any vertex is enque in queue, it makes status change, so that no any node is processed more than
once, so status is used for every vertex.
ALGO:-

Step 1: Initialize all nodes to ready state.


[Status = 1]
Step 2: Put the starting node A in queue.
Step 3: Change status of A by 2
Set status of A = 2 [waiting state]
Step 4: Repeat steps 5 to 9 until queue is empty.
Step 5: Remove front node N of queue.
Step 6: Process N.
Step 7: Change state of N by 3
Set status of N = 3
Step 8: Add all the neighbours of at rear in queue that are in ready state.
Step 9: Change their status to 2
End of loop.
Step 10: Exit.
DFS: [Depth First Search]
 Stack structure is used.
 Justify starting node a
 Find out all the adjacent vertex of A
 Push these all vertex in stack
 Pop vertex from stack and so on.
 Different status for vertex is also used to identify that which vertex has been processed or not.
Algo 1:
Step 1: Initialize all to the ready state.
[Set status of all node = 1]
Step 2: Push starting / source vertex A onto stack.
Step 3: [Change the status of A by 2]
Set status [A] = 2
Step 4: Repeat steps until stack is empty.

 Vidhya Institute of Information Technology 


146
Ideal ‘Data Structure’

Step 5: Pop the top node N of stack.


Step 6: Process N
Step 7: Change the status of N by 3
Set status [N] = 3
Step 8: Push all the neighbours of N in stack, whose status is 1.
Step 9: Change the status of these all nodes by 2
Set status = 2
End of loop
Step 10: Exit.

Minimum Spanning Tree [MST]


 A spanning tree for a graph G = (V,E) is a sub group of G that is tree.
 It contains all the vertex of G.
 It is created only when graph is weighted.
 A MST for weighted graph is a spanning tree with minimum weight.
 If a graph G with n vertex , then the MST will have (n-1) edges.
 A weighted graph may have more than one MST
 If graph is no connected it can not have MST.
 MST is used when
 We want to find cheapest way to connect vertex of 0 graphs.
 Used in routing algorithm, which finds efficient paths through a graph that visit every vertex.

 To find out the MST of a graph, two type of algorithm can be used.
 Kruskal’s Algorithm
 Prims Algorithm
 Both type of algorithm can be used
 Output is always same, means both will create same tree.
 Technique of these algo is different.

KRUSKAL’S ALGORITHM
This algo is used to find out the MST.
Algo:-
Step1: Write the pair of all adjacent vertexes with their weight.
Steps 2: Arrange these all pairs in ascending order according to their weight.
Steps 3: Connect these vertex pair one by one in order but cycle does not create.
Step 4: If any vertex pair creates a cycle ignore it move to next pair.
Step 5: Repeat steps 3 until all pair has processed.
Step 6: Finally it will be MST.
2
Step 7: Exit A B
4
For example: 3 6

7 G 2 F
1 4

2
C D
5

6 1

Step 1: = pair of all neighbour vertex with weight


AB-> 2
AC->7
AG->3
CD->5
CE->6

 Vidhya Institute of Information Technology 


147
Ideal ‘Data Structure’

CG->1
DB->2
DG->4
DF->2
DE->1
BG->6
BF->4
STEP 2: arrange them in ascending order by weight.
CG->1
DE->1
DF->2
DB->2
AB->2
AG->3
DG->4
BF->4
CD->5
CE->6
BG->6
AC->7

STEP 3: connect these pair one by one but cycle not occur
CG->1 DE->1
G G
1 1

C C

D
1

DF-> 2 DB-> 2
G B
1
F
C 2 G
1 2 F
2
D C
1
D
1
E
E
AB->2 AG->3

2 2
A B A B
G
3 2
2 F G F
G
1 2 1 2

C C
D D
1 1

E E

 Vidhya Institute of Information Technology 


148
Ideal ‘Data Structure’

Dg-> 4, BF-> 4, CD-> 5, CE-> 6, BG-> 6, AC-> 7, not connected because they create cycle and MST can not
have cycle in any case.

Now finally MST is->


2
A B
G
3 2
G F
1 2

C
D
1

Finally cost of a tree = Sum of edges weight


Cost (Tree) = 2+3+1+2+2+1 =11

PRIM’S ALGORITHM
This algo is used to find out the MST by given weighted graph G.
Algo
Step 1: Take any vertex as a source vertex A of group G.
Step 2: Write its all adjacent vertex with their weight.
Step 3: Write ∞ for remaining vertex which are not adjacent of A.
Step 4: Finds the adjacent vertex N whose weight is minimum or lowest.
Step 5: Connect this vertex N with A but cycle does not occur in any case and ignore remaining vertex
Step 6: Repeat step 2 by making N as A [source vertex] until all vertex connect in MST and once connected vertex
must not occur again.
Step 7: Exit

For eg:-
2
A B
2
1 3 1
1
5
F G E C

2 2 1 1
2
H I D
1

 Vidhya Institute of Information Technology 


149
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


150
Ideal ‘Data Structure’

Path matrix
 When we create the adjacency matrix for a graph (G), then it shows only direct path
between vertices
 But it may be possible that any undirected path may be these between any two vertices.
 Such type of matrix which displays the direct & undirect path between any two vertices
is called path matrix.
 Number of different - different algos is these to find out the path matrix.

1. General Algo
2. Warshall Algo
General Algo
Step 1: Create a adjacency matrix (A) of given graph (G)
Step 2: Create or find out matrix
pm = A1 +A2 +A3------------+An
[Here m = no of vertices]
Step 3: Replace the non-zero entry of pm with 1 and other is already zero.
Step 4: Create new P matrix with logic of step 3.
[Now this P is path matrix]
e3
Step 5: Exit. A D
e4 e5
For eg:- graph(G) e2 e6
e1

Now here B
e7
C
Adjacency matrix (A)=

m=4 Adjacency matrix


m is use to represent the total number of nodes
A B C
A is use to represent the adjacency matrix D

pm = A+A2+A3+A4 A=

A2 = A X A =

 Vidhya Institute of Information Technology 


151
Ideal ‘Data Structure’

A3 = A 2 X A =

A4 = A 3 X A =

Now pm = A+A2+A3+A4

pm replace all non zero elements by 1.

Warshall algorithm
 Previous algo is a very complex algo.
 Because if number of node increases, then m time matrix has to multiplied so it become complex.
 Warshall provide an easy way to find out path matrix.
 In this algo, first of all direct path matrix (P) has to create with help of adjacency matrix (A).
 Pij contain all elements with zero where Aij = 0 otherwise Pij = 1

 Vidhya Institute of Information Technology 


152
Ideal ‘Data Structure’

Algo:

Step 1: Repeat for i, j, = 1, 2, ------M;


if A[i,j] =0 then
set p[i,j] = 0
else
set p[i,j] = 1
End if
End of loop
[This logic will create Direct Path Matrix P]

Step 2: Repeat step 3 and 4 for K= 1,2, 3 ----M;


Step 3: Repeat step 4 for i= 1, 2---- M
Step 4: Repeat step j = 1, 2 ------ M
set p[i,j] = p[i,j] V (p[i,k] ^ p[k,j])
End of loop
End of step 3 loop
End of step 2 loop
Step 5: Exit.
Shortest Path Algorithm or Dijkastra Algorithm
 Warshall and general algo find only path matrix.
 But suppose we want to find out the path between two vertex which one is smallest or shortest.
 Because there may be number of path between any two vertex.
 Dijkastra algo provides an efficient way to provide shortest path.
 To find out the shortest path, weight must be there for every edge.
 Without weight shortest path can not be found if weight not given consider by 1;
 This diskastra algo use weight matrix to find the shortest path.

Algo Contain
1 A weighted graph G
2 M nodes
3 W weight matrix
4 Q matrix: -
Q[I,j] is the length of shortest path from node vi to vj
5 Infinity: is a very large number.
used initially in Q where no any path between vi & vj
6 MIN: It is a function which returns minimum value which is used to find short path.
Basically our goal is to replace this all infinity with shorted path weight value
DIJKASTRA ALGO
Step 1: Repeat for i = 1, 2---------m
if w [i, j] = 0, then
set q [i, j] = infinity
else
set q [i, j] = w [i, j]
end if
end of loop

Step 2: Repeat step 3 and 4


for k = 1, 2------M
Step 3: Repeat steps 4
For i= 1, 2------- M
Step 4: Repeat
For j = 1, 2 --------M
set Q[i,j] = MIN (Q[i,j] , Q[i,k] +Q [k,j] )
end of loop j
end of loop i
end of loop k
Step 5: Exit.

 Vidhya Institute of Information Technology 


153
Ideal ‘Data Structure’

SEARCHING
 Our computer system can store large amount of data of different – different types as in
form of files
 And if there is any need to retrieve them again, then there is a requirement to search the
required data. So at that time the concept of searching comes into existence.

 Searching is a process of finding the element, that either it is available is structure or not
 Searching is one of the basic technique to also find the location of an element in any
structure if it is available in it.
 Searching is one of the most basic operation and important operation of “data structure”
or any “data organization “
 Generally every data structure requires searching.
 Always fast searching is preferred.

 Searching may be a very “time consuming process” and time complexity increases if
number of elements in structure exceed.
 While using searching technique, three different types of cases considered.

[A] BEST CASE

[B] AVERAGE CASE

[C] WORST CASE.

(A) BEST CASE: - It is a case, where element found at first location or in first
comparison or almost at starting locations in data structure:
“It is preferred case”

(B) AVERAGE CASE: - It is a case, where element found at mid location or almost at
mid location, that is average case.

(C) WORST CASE: - It is a case, where element found at last location, or almost last
locations of data structure that is worst case.

 Last level of worst case is that element not found in data structure.
 “It is not preferred case”
 Selection of case is not in our hand. It depends on the structure’s type or element in the
structure.

 Vidhya Institute of Information Technology 


154
Ideal ‘Data Structure’

We have two types of Searching: -

(1) Linear search


(2) Binary search
Both types of searching can be used in our implementation but which one is
better depend on the organization of the elements or order of elements with in our
structure.
Every searching has its advantage & disadvantages explain below one by one.

“Linear Search”
Linear search is also known as:
Sequential Search
One by one Search
Step by step Search
Concept: -
In the linear search technique given element is compared with the every element
of the structure one by one as name implies.

When element is given, then this element is composed with every location of available
structure in linear form, and when element is found then according to requirement searching
stop here.
The element is search is linear form or search sequentially that’s why it is called as Linear or
Sequential Search.
“Suppose there are n elements”.

Best Case Element found as first or almost first location.


Average Case Element found as first or almost first location.
Worst Case If element found at nth location.
If element not found.

Major disadvantage of Linear Search


Suppose n elements are there and if search element is available at last location or not
found then n comparison done.
And if number of elements (n) is more in structure then it takes more time that’s why
linear search is very time consuming process.
Complexity increases if n increases.
Efficiency of linear search decreases if n increases.
Major Advantage of Linear Search
Linear search, check or compare every element one by one. So if element is available in
structure, then sure linear search locate it.
Elements can be arranged or organized in any order
It should prefer if you are sure that element is available is structure to find the
location of that element) .
 Implementation is easy
 Take less memory (implementation variable)
 Practically not complicated.
 If number of same elements is available, then these all elements can also
search by linear search.
Conclusion
If you are sure that element is available & you want to find out the location of that element,
it preferred.

 Vidhya Institute of Information Technology 


155
Ideal ‘Data Structure’

The process of linear search is similar to that if you want to find the locations of your
known person in any line or queue.

Technical Concept
Suppose there is structure a with n element.
You want to search k element & its location in a then,
Compare every element of a with k
if found then
stop searching
otherwise
Check or compare all n elements.
So a[i] compare with K
where I =1, 2-----------upto n

Algo of Linear Search


Step 1: Start the program.
Step 2: Input number of elements in n.
Step 3: Ask/Input n elements in structure a one by one.
Step 4: Input element in K which you want to search.
Step 5: Set i=1
Step 6: Repeat Step 7 to 9 while i<=n
Step 7: Check if a[i] =k then
Display “Element found at”, i
exit
end if
Step 8: set i=i+1
Step 9: go to step 6
Step10: display “element is not found”

 Vidhya Institute of Information Technology 


156
Ideal ‘Data Structure’

IMPLEMENTATION OF LINEAR SEARCH


#include<process.h> SEARCHING
#include <stdio.h>
#include<conio.h>
#define max 10
void main ()
{
int n, i, a[max], k ; clrscr();
printf(“\n enter how many elements:-“);
scanf(“%d,&n”);
if (n>max )
{
printf(“\n input size is greater than declared size”);
getch();
exit(0);
}
printf(“\n enter %d elements in array n”);
for (i=0; i<n;i++)
{
printf(“\n enter element:-”):
scanf(“%d”,& a[i]);
}
clrscr();
printf(“\n enter the element which you want to search”):scanf(“%d”,&k);
/* logic of linear search*/
for (i=0; i<n; i++)
{
if (a[i]= = k)
break;
}
if (a[i]= = k)
printf(“\n %d elementfound at [%d] location”k ,i);
else
printf (“\n%d element not found” k);
getch();
}
Previous implementation searches the element if its single copy is maintained.
But if we want to search all presence of k in structure then use following technique:
#include<process.h>
#include<conio.h>
#include<stdio.h>
#define max 10

void main()
{
int a[max],n,i,k flag =0;
clrscr();
printf(“\nenter how many element :-”);
scanf(“%d”&n);
if (n> max)

 Vidhya Institute of Information Technology 


157
Ideal ‘Data Structure’

{
printf(“\n input size is greater than the declared size”);
getch();
exit(0);
}
printf(“\n enter %d element in array ”,n);

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


{
printf(“\n enter the element :- ”);
scanf(“%d”,&a[i]);
}
clrscr();
printf(“\n enter element which you want to search”)
scanf(“%d”,&k);
for( i=0; i<n; i++)
{
if (a[i] = = k)
{
printf(“\n %d element found at [%d] location ” k,i);
getch(); // only hold the search
flag =1;
}
}
if (flag = =0)
printf(“\n %d element not found” k);
getch();
}

The above Technique Working is as follow


Flag by default initialize with 0.
Comparison will done n time and in these comparison whenever element found, its location
displayed on the console and flag set to 1.
Value of flag is set to 1, because with this value we can identify that either element found or
not after these all comparisons.
Because if element k is not available, then value of flag will 0. So we again check if it is zero
it means value k not found.

BINARY SEARCH
 It is a most advance form of linear search.
 It is based on “divide & conquer” technique.
 It is discovered to reduce the time in searching.
 This technique is similar to search any word in English dictionary.
 One condition is that all elements must be stored in any order either Ascending or
Descending.
 If elements are not arranged in order, this technique becomes fail.
 As we say that it is based on Divide & Conquer technique, means:
o In this technique entire structure is divide in two halves (part)
o Then required operation (searching) is performed by selecting appropriate value.

 Vidhya Institute of Information Technology 


158
Ideal ‘Data Structure’

o Means only in one half searching will be done.


o If element not found, again selected half divide in two parts again.
o Do that process continue again & again until element not found or when
division of structure is not possible.
For example, suppose there are 500 elements then searching will done in following procedure:

500

0 to 250 251 to 500

 At this part any one half or part will eliminate


 By finding out which can contain our searching element.
 This thing is possible because we known that all element are sorted. So we can find that
which part can contain element.
 Again we divide selected half in two part
 Again selected appropriate half out of them
 This process continue when element not found at[mid] location, it is a location where
structure divide in two halfs.
 So according to the element which is situated at mid, left or light values will selected if
element not found at mid.
 We are saying that n is faster because in first time comparison, just half elements are
eliminated from searching.
 Second time again half elements are eliminated & so on.

Practical Implementation with example


To implement the binary search, here we have to maintain three variables for holding
locations
l = lower bound of a half
u= upper bound of a half
mid = mid location of lower (l) & upper (u) bound
Initially
l=1
u=n (total elements)
then mid = (l+u)/2

For eg
Suppose we have 10 elements stored in structure a in ascending order and we want to
locate 25 in this structure.

10 elements are:
Location 1 2 3 4 5 6 7 8 9 10
10 18 25 34 57 62 69 72 85 90

Here l=1, u=10, mid 5 (integer part because decimal locations is not possible in any structure)
k=25; element location, which we want to search.
Step1: Check k not available at a [mid]
a[mid] =57
k=25 (not)
divide structure in two parts.

 Vidhya Institute of Information Technology 


159
Ideal ‘Data Structure’

Part1: l to mid -1 (left part)


Part2: mid + 1 to u (right part)

Mid is not included because element is not available at mid.

Step2: Select part 1 either part 2, which can contain k element.


How we can justify this?
 We know that elements are stored in sorted (ascending) order.
 At mid location there is 57,
o So obviously 25 will be in left part
o Only now left part will be searched for k element.
For doing so, bounds of structure will change.
Now left part is considered
So l = 1
but u = mid-1 (5-1=4)
New searching structure will be:
I=1 to u=4
1 2 3 4
10 18 25 34
Again mid = (l+u)/2 => (1+4)2/2

Check a[mid] = k, a[2] =25

18  25 (false)
Again make two part

Part1: l+mid +1 [left part]


Part2: u=mid-1 [right part]
mid location value is low so here we have to more lower bound and left part will be
considered.
l=mid +1 => 2+1 =>3
u=4
Again mid (l+u)/2 =7/2 =3
New value - 3 4
25 34
Check a [mid] =k, a [3] =25
25= 25 (true)
Now finally k found at mid location that is 3.
 In this way binary search work.
 Here we create two halves again & again & then we are searching, that’s why that
searching is based on divide & conque technique.
 It element not available then always a [mid]  k, but at where we divide the structure,
that’s why we have to use another condition. Because if we consider only a [mid]  k
condition then in the absence of k it will infinite.

So another condition is:


(l) lower bound<= upper bound (u)
 Because when upper bound will become less than lower bound, it means element not
found.

 Vidhya Institute of Information Technology 


160
Ideal ‘Data Structure’

 Because if they cross each other, then they move in this direction then directions (value)
are already searched and it will also become infinite.
 So when ever l<=u, comparison will done or continue.
------------------u ----- l------------
l-------------- ---------------u
Practical Implementation of Binary Search
#include<conio.h>
#include<stdio.h>
#include<process.h>
#define max 10
void main ()
{
int a[max] k,i,l,mid,u,n;
clrscr();
printf(“\n enter how many element:-”);
scanf(“%d”&n);
if (n>max)
{
printf (“\n size out of array-:”);
getch();
exit(0);
}
printf(“/n enter %d sorted elements in array:n”);
for(i=0;i<n;i++)
{
printf(“\n enter element:-”);
scanf(“%d”&a[i]);
}

clrscr();
printf(“\n enter element which you want to search:-”);
scanf(“%d”&k);
/* logic of binary search*/
l=0;
u=n-1;
mid=(l+u)/2;
while (a[mid]!=k && l<=u)
{
if (a[mid]>k)
u= mid -1; // move to left array
if (a[mid]<k)
l=mid+1;// move to right array.
mid =(l+u)/2; // again two part with new bound
}
if (a[mid]= = k)
printf(“\n %d element found at [%d] location,” k,mid);
else
printf(“/n %d element not found ” k);
getch();
}

 Vidhya Institute of Information Technology 


161
Ideal ‘Data Structure’

Major Advantage of Binary Search


 Basically we use various types of techniques to remove drawbacks of previous
technique.
 Binary search is used to overcome the drawback of linear search.
 Binary search takes so much less time in compare to linear search.
 It makes searching easy.
 It is a very fast searching technique.
 It’s complexity appears in logarithmic notation
 Suppose 50 elements are to search
 Worst case of linear search is 50 comparisons.
 Worst case of binary search is 7 comparisons.
(50 25 12 6 3 2 1)
1 2 3 4 5 6 7
(It makes two halves)
Disadvantage of Binary Search
As we know that if we are using binary search for searching any element then there
elements must in sorted order.
So this is the one of the most major disadvantage or cons of binary search.
Binary search always require that elements must sort, but in real life it is not possible
element may be available in any order. Here binary search will fail.
Its implementation is complex than linear.
If single element is not sorted and if it is in opposite part of structure binary search will
become fail in searching that elements.
Implementation requires higher memory than linear search.
It does not help in searching element which is number of times available in structure
(generally).
A data structure which use pointers, binary search is not possible.
Conclusion
 If your elements are sorted in an order, then binary search is too good to search element
 If given element are not sorted, then by any sorting they can be sorted, after binary
search can apply:
(but) it will become n time complex [o(n2)]at the place of this directly linear search can
be used[0(n)].

SORTING
Sorting is one of the most important types of operation of data structure of any type.
Sorting is a process of arranging the element of structure in any logical order. This order
either can be Ascending or Descending.
 Sorting make searching so fast.
For example:-
 We can easily search any word of English in dictionary because all words are arranged in
ascending order.
Similar to that, to improve the searching or efficiency of our structure, we use the
concept of sorting.
 Binary search is much better than linear search, because linear search is time consuming
process but if we prefer binary search, condition of binary search is that all elements
must be either in ascending to descending order otherwise binary search is not possible.
 So to arrange the elements of a structure in any order, the concept of sorting is used.

 Vidhya Institute of Information Technology 


162
Ideal ‘Data Structure’

 Sorting can be done on both either numerical or alphabetical values.


Basically there are two types of sorting:
1. External sorting
2. Internal sorting

1. External Sorting
 This is process of arranging the elements or data which are stored in data files
(permanent storage).
 This sorting is done when there is a large amount of data is available.
 This sorting is used with the data which are available in auxiliary memory such as hard
disk, floppy disk or permanent storage.
Example are :>
 Merge sort
 Radix sort

2 . Internel Sorting: -
 This is a process of arranging the elements or data which are stored in computer’s main
memory (temporary files)
 This sorting is done when low amount of data is available.
 When one pass complete, and then in second pass, last element will not be compared.
Because it is already sorted.
 If there are n elements in the structure then n-1 pass will occur, because in the last n
pass, already smallest element will be at top(0) so no need to compare with it to all again.
 Means every jth element of an array will be compared with j+1th element, if greater, than
both will be swapped.
 a j compare with a j+1 with greater condition.
if (a[j]>a [j+1])
 Then aj swapped with aj+1
t=a[j]
a[j] =a[j+1]
a[j+1] = t
 Internal steps where n(total element) = 5

a[0] compare with a[1]


a[1] compare with a[2]} first pass
a[2] compare with a[3]} (if require than swap)
a[3] compare with a[4]
Examples are:-
Bubble sort
Selection sort
Insertion sort
Quick sort
Heap sort
Shell sort

BUBBLE SORT
One of the most general types of sorting is bubble sort.
Concept of bubble sort
 Every element of the structure compared with its next element.
 If it is greater, then swap this with its next one.

 Vidhya Institute of Information Technology 


163
Ideal ‘Data Structure’

 This process will continue until every element is compared with its next one.
 When all elements are compared with its next then this is known as “Pass”.
 When one pass complete, the largest element is arranged at last position (ascending).
 With another pass that is second pass, the second largest element will be stored at
second last position.
 And so on.

Example: -
Suppose following numbers are stored in array a.
23, 99, 87, 58, 66, 32, 11
 Sorting of array a in ascending order by bubble sort technique:
Here n=7 (total elements of a)

pass 1 :

23 23 23 23 23 23 23
99 99 87 87 87 87 87
87 87 99 58 58 58 58
58 58 58 99 66 66 66
66 66 66 66 99 32 32
32 32 32 32 32 99 11
11 11 11 11 11 11 99
 After one pass largest 99 will be at last position, no need to check it again.
 So on the next pass checking or comparison loop will run but less one

Pass 2:

23 23 23 23 23 23
87 87 58 58 58 58
58 58 87 66 66 66
66 66 66 87 32 32
32 32 32 32 87 11
11 11 11 11 11 [87]
[99] [99] [99] [99] [99 ] [99]

 After second pass second largest (87) will be at second largest position.
 So in the next pass comparison, loop will run but less two, because two elements have
sorted.

Pass 3: -
23 23 23 23 23
58 58 58 58 58
66 66 66 32 32
32 32 32 66 11
11 11 11 11 [66]
[87] [87] [87] [87] [87]
[99] [99] [99] [99] [99]
 After pass 3, third largest (66) arrange at third last position.
 So in the next pass total comparison will less three

 Vidhya Institute of Information Technology 


164
Ideal ‘Data Structure’

Pass 4:
23 23 23 23
58 58 32 32
32 32 58 11
11 11 11 [58]
[66] [66] [66] [66]
[87] [87] [87] [87]
[99] [99] [99] [99]

Pass 5:

23 23 23
32 32 11
11 11 [32]
[58] [58] [58]
[66] [66] [66]
[87] [87] [87]
[99] [99] [99]

Pass 6:
(n-1) pass Final array is:
[23] 11
[11] [23] [11]
[58] [32] [23]
[58] [58] [32]
[66] [66] [58]
[87] [87] [66]
[99] [99] [87]
[99]

By seeing above pass we can establish following relations:


 Total passes => n-1
Where n=total elements of an array
 Total comparison in every pass =>
n –i
Where i=pass number
(i) Pass no. Total comparison
1 7-1 =>6
2 7-2 =>5

 After every pass the largest element will be placed in nth position.
 The next largest element will be placed at (n-1), (n-2)…………2 respectively.

 Vidhya Institute of Information Technology 


165
Ideal ‘Data Structure’

Practical Implementation of Bubble Sort


Program :>
void main ()
{
int a[10], n, i, j, t;
clrscr();
printf(“\n enter how many elements in array”);
scanf(“%d”,&n);
if(n>10)
{
printf(“\n size out of array”);
getch();
exit (0); // terminate the program
}
printf (“\n enter %d element in array”);
for(i=0;i<n; i++)
{
printf(“/n enter %d location element :-”);
scanf(“%d”, &a[i]);
}
clrscr();
printf(“/n/n element before sorting are :-”);
for (i=0;i<n;i++)
{
printf(“/n %d location element is :-%d” i,n);

/* logic for bubble sort */


for(i=0;i<n; i++)
{
for (j=0;j<n-1-i; j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j] =a[j+1];
a[j+1] =t;
}
}
}
}
printf(“/n element after ascending order bubble sort ”);
for(i=0; i<n;i++)
printf(“%dlocation element is :-%d” I,a[i]);
getch();
}

 Vidhya Institute of Information Technology 


166
Ideal ‘Data Structure’

ADVANCE OR MODIFIED VERSION OF BUBBLE SORT


Bubble sort has a very important property:
Once there is no swapping of elements in a particular pass, there will be no further swapping of
elements in remaining passes.
But
This property does not implemented by the above logic.
Now we will implement this logic is next program.
Means, if any number is not swapped in any pass that means all elements are already sorted. So
no need to compare them again. It is also a wasting of time. To overcome this problem we
follow this logic:
for (i=0; i<n; i++)
{
flag =0;
for(j=0; j<n-1;j++)
{
if (a[j]>a[j+1])
{
t=a[j]
a[j]=a[j+1];
a[j+1]=t;
}
flag =1;
}
}
if (flag = = 0)
break;
else
flag = 1;
}

 By using this logic already sorted list will not check.

SELECTION SORT
Another and again simplest of sorting is a selection sort.

Concept of Selection sort: -


Every element of the structure is compared with the element which is smallest among
remaining element.
If element is greater than smallest one then they will be swapped.
 This above process will continue until every element is compared with smallest among
relative Element.
 When first element is compared with smallest among remaining element, this is called
one pass (first pass).
 In first pass, the smallest element place a at 0th location of an array.
 Similarly in second pass the second smallest element placed at 1st location
 There will also n-1 passes.
 Here every ith position, element is compared with smallest element among i+1 to nth
element of an array.

 Vidhya Institute of Information Technology 


167
Ideal ‘Data Structure’

 If ith position element is greater than smallest then they are swapped with each other
otherwise, no swapping will occur.
(Saving of time)

n=7, total element


 a [0] is compared with 1 to n-1 element’s 0smallest element.
 a [i] is compared with smallest among 2 to n-1 element.
 ………..so on.

Example -:
Suppose we have following element with in array a:

78 34 45 12 89 23

Sort this element with the help of selection sort:

Pass1:

78 34 45 12 89 23

i=0
a[i] = 78 compare with smallest between a+1 to n
min=> 12
location of 12 =3, that is loc = 3

if (a[i] >min )
{
t=a[i];
a[i] = a[loc];
a[loc] =t;
}

[12 ] 34 45 78 89 23

Pass 2:

(12) 34 45 78 89 (23)

Here a[i] =34, i=1


min = 23
loc =5
Swap a[i] with a[loc] (if i!=loc)
After that
[12] [23] 45 78 89 34

 Vidhya Institute of Information Technology 


168
Ideal ‘Data Structure’

Pass 3:

(12 ) (23) 45 78 89 (34)

a[i] =45; here i=2


Min=34
loc =5
Swap a[i] with a [loc] , if i! = loc
After that
[12] [ 23] [34 ] 78 89 45

Pass 4:

[12] [23] [34] 78 89 (45)

a[i] =78, here i=3


min = 48
Loc =5

Swap a[i] with a [loc], if i! =loc


After that

[12] [23] [34] [45] 89 78

Pass 5:

[12] [23] [34] [45] 89 (78)

a[i] =89, here i=4


min = 78
loc =4
swap a[i] with a[loc] (if i! = loc)

[12] [23] [34] [45] [78] [89]

Now by seeing the above passes we can establish the following relations:
 Total pass = n-1
Where n = total elements of an array
 Total passes = i=0 to n-1>
 Smallest element selection range
start = i+1
end = 1
 loc hold the location of smallest element among remaining element
 Initially loc contain pass value
 If loc not equal to I then swap the values of a loc and a [i] because if both are equal then
no mean of swapping.

 Vidhya Institute of Information Technology 


169
Ideal ‘Data Structure’

Implementation of selection sort

void main()
{
int a[10] , I,j,loc, small, t,n;
clrscr();
printf(“/n enter the how many element -: ”);
scanf(“%d”,&n);
if (n>10)
{
printf(“/n size out of array”);
getch();
exit(0);
}
printf(“/n enter total element in array ”a);
for (i=0; i<n; i++)
{
printf(“/n enter %d element-:”);
scanf(“%d”, &a[i]);
}
clrscr();
printf(“/n element before sorting are -”);
for (i=0; i<n; i++)
{
printf(“/n%d”, a[i]);
}
/* selection another sort logic */
for (i=0; i<n-1;i++)
{
loc =I;
min = a[i];
for (j=i+1; j<=n-1;j++)
{
if (a[j]< min)
{
min = a[j];
loc =j;
}
}
if (loc !=i)
{
t=a[i];
a[i] = a[loc];
a[loc] = t;
}
}
printf(“/n elements after sorting are ”);
for (i=0; i<n; i++)
printf(“/n %d”, a[i]);
getch();
}

 Vidhya Institute of Information Technology 


170
Ideal ‘Data Structure’

Insertion Sort
It is a special type of sorting.
“In this technique, we pick a particular value y and then insert or place it at the
appropriate place in the structure”.
 Here every element of the structure is compared with all its previous elements.
 If previous element is greater than y then this element is moved to its next location.
(Here we use concept of array, so copy will move to next location, actual location will
not become (empty)
 This process is continued for last element, means when last element is compared with all
its previous elements then sorting will complete.
 Here every pass will be checked with all previous elements.
 If there are n elements then (n-1) pass will be performed.
 After (n-1) passes, the array or structure will become sorted.
 Every ith location element is compared with all previous i-1 location until I become 0.
If previous one is small then no element is moved, otherwise ith element will move to
i+1 location, so we can make a room or place for this ith element with in a structure.

“We insert the element at particular location which we have select, so this technique is
called Insertion Sort”.
a[0] compare with  no comparison
because this location has no previous elements.
a[1] compare with  a[0]
a[2] compare with  a[1], a[0]
a[3] compare with  a[0], a[1], a[2]
a [4] compare with  a[0], a[1], a[2], a[3]

Here are total 5 elements.


If previous element is already small then no need to move it to its next location and no
further comparison because all these previous elements are already sorted. We always
move to every element with sorting logic, that’s why elements are already sorted.

For example [Square brackets [ ] represent element which is being compared round
brackets represent Y]
77 33 11 44 88 99 55 22

Pass 1 :
Selected element is y =33, because 77 has no previous element

y=33

[77] (33) 11 44 88 99 55 22
“77 will move to next location” (33 location)

77 77 11 44 88 99 55 22
All element has been tested then 33 is placed at first location
33 77 11 44 88 99 55 22
In this way all pass will occur.

 Vidhya Institute of Information Technology 


171
Ideal ‘Data Structure’

Pass 2:
33 77 (11) 44 88 99 55 22
y=11
33 [77] (11) 44 88 99 55 22
[33] 77 11 44 88 99 55 22
33 77 11 44 88 99 55 22
Now finally
11 34 77 44 88 99 55 22

Pass 3:
11 33 77 (44) 88 99 55 22
11 33 77 44 88 99 55 22

y=44 11 33 77 44 88 99 55 22

y =44 11 33 77 44 88 99 55 22

y=44 11 33 33 77 88 99 55 22

No shifting
Finally
11 33 44 77 88 99 55 22

Pass 4:

11 33 44 77 88 99 55 22
11 33 44 77 (88) 99 55 22

y=88 11 33 44 77 88 99 55 22
11 33 44 77 88 99 55 22
Here 88 is already greater than with its previous element(77) then it will not be
moved and no further comparison will occur.
Because we are at (88) by sorting its entire previous element. So no need to
compare, even if we compare then no any element will moved.

Pass 5:
11 33 44 77 88 (99) 55 22

y=99 11 33 44 77 88 99 55 22
Same as pass 4 no need to move

Pass 6:
11 33 44 77 88 99 55 22

y=55 11 33 44 77 88 99 55 22

y=55 11 33 44 77 88 (99) 99 22

y=55 11 33 44 77 88 88 99 22

y=55 11 33 44 77 77 88 99 22

 Vidhya Institute of Information Technology 


172
Ideal ‘Data Structure’

No movement
So
11 33 44 77 88 99 55 22
That is final array of pass 5, which use for pass 6.

Pass 7:
11 33 55 77 88 99 (22)

y=22 11 33 55 77 88 99 22

y=22 11 33 55 77 88 99 99

y=22 11 33 55 77 88 88 99

y=22 11 33 55 77 77 88 99

y=22 11 33 55 55 77 88 99

y=22 11 33 33 55 77 88 99
No movement (place y at compared +1 location)
y=22 11 22 33 55 77 88 99

Now array= 11 22 33 55 77 88 99

It is final array after sorting, which is sorted.

Practical implementation of insertion sort: -


#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[10] ,n,I,j,k;
clrscr();
printf(“/n enter the how many element”);
scanf(“%d”,&n);
if(n>10)
{
printf(“/n size out of array capacity”);
getch();
exit(0);
}
printf(“/n enter %d elements in array” n);
for (i=0;i<n; i++)
{
printf(/n enter [%d] location element -:);
scanf(“%d”&a[i]);
}
Clrsccr();
printf(“/n element before sorting ”);

 Vidhya Institute of Information Technology 


173
Ideal ‘Data Structure’

for (i=0;i<n;i++)
printf(“/n%d”,a[i]);
getch();
/* logic for insertion sort */
for (k=1; k<n;k++)
{
y=a[k];
for (i=k-1; i>=0 &&y<a[i]; i++)
{
a[i+1] =a[i];
}
a[i+1] =y;
}
printf(“/n elements after sorting are ”);
for (i=0; i<n;i++)
printf(“/n %d”, a[i]);
getch();
}

Note: -
The following logic can also be used for following condition for insertion sort.
 Output & working of both logic is same.
/* Another logic of insertion sort */
for(k=1;k<n;k++)
{
y=a[k];
i=k-1;
while ((i>=0) && (y<a[i]))
{
a[i+1] = a[i]
i--;
}
a[i+1]=y;
}

SHELL SORT

This type of sorting is one of the most advance forms of bubble sort.
Logic: - This type of sorting makes multiple passes of array and each time sort the number
which are at equal distance (d).
This technique is similar to bubble sort that it also check every element but not with its next
element.
In this sort every element is compared with the element which is sorted at fixed location d,
and after that again next element is compared with the element which is stored at same dth
location.
This location d also varies with every element which you are comparing with.
Suppose there are n elements in the data structure.
Every element of this structure will compare with d distance element where
d=mid location of structure [d=n/2]

 Vidhya Institute of Information Technology 


174
Ideal ‘Data Structure’

In next pass, again every element compare with its d distance element but now d will be round
half of previous d that is [d=d/2.0+0.5].
This entire process continues until d become 1.
During comparison, if d location element is smaller than ith location element, then swapping
will be performed.
Means every ith location element is compared with (i+d)th location element and if (i+d)th
element is smaller, then both will interchange to each other.
After that d become d/2.
Again same process will be continued until d become 1
if (a[i]>a[i+d])
{
t=a[i]
a[i]=a[i+d];
a[i+d]=t;
}
Suppose n=6 then d=n/2 =3

In pass 1
a[0] compare with a[3]
a[3] compare with a[6]
For eg:- An array contains 7 elements in following order:
12 9 -10 22 2 35 40
Pass 1:
12 12 12 12 12
9 9 2 2 2
-10 -10 -10 -10 -10
22 22 22 22 22
2 2 9 9 9
35 35 35 35 35
40 40 40 40 40

Pass 2:
d=d/2 > 3/2 = 1.5 +5>2
12 -10 -10 -10 -10 -10
2 2 2 2 2 2
-10 12 12 9 9 9
22 22 22 22 22 22
9 9 9 12 12 12
35 35 35 35 35 35
40 40 40 40 40 40

Pass 3 d= d/2 => ½ => .5+.50/

-10 -10 -10 -10 -10 -10 -10


2 2 2 2 2 2 2
9 9 9 9 9 9 9
22 22 22 22 12 12 12
12 12 12 12 22 22 22
35 35 35 35 35 35 35
40 40 40 40 40 40 40

 Vidhya Institute of Information Technology 


175
Ideal ‘Data Structure’

Now, finally we can say it is most short of bubble sort and it require very less
pass to sort elements where as it element increases then passes will also increase means n
elements require n-1 pass, where as shell sort require very less pass.
That’s why shell sort is better than bubble sort.
Pratical implementation of shell sort
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[10],n,I,d;
clrscr();
printf(“enter how many element ”);
scanf(“%d”,&n);
if(n>10)
{
printf(“/n size out of array ”);
getch();
exit(0);
}
printf(“/n enter %d element in array”n);
for(i=0;i<n; i++)
{
printf(“/n enter [%d] location element ” i);
scanf(“%d”, &a[i]);
}
clrscr();
printf(“/n array element before sorting ”);
for(i=0: i<n; i++)
{
printf(“/n %d,”,a[i]);
}
getch();
/* logic of shell short */
d=n/2;
while (d>=1)
{
for (i=0; i<n-d:i++)
{
if (a[i] > a[i+d])
{
t=a[i];
a[i] =a[i+d];
a[i+d] =t;
}
}
if (d==1)
Break;
d=d/2.0 +0.5;
}
printf(“/n elements after sorting :-”);

 Vidhya Institute of Information Technology 


176
Ideal ‘Data Structure’

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


printf(“/n %d”, a [i]);
getch();
}
MERGE SORT
 This sort technique based on
“Divide & Conquer Technique”
 Basically in this sorting the array divide into two parts.
 These parts again divide into two subparts.
 This process continues until the numbers of elements in the array are not more than 1.
 Then sort these elements become so easy because there is single – single element in
every array.
 After sorting again, merge these arrays with in single one.
 Finally that array will be sorted.
 Basically it is a “recursive” technique.
 Suppose beg and end represent the index of the first and last element of array, then
merge sort can be defined as
if (beg<end) then
Divide the list in two parts
Sort the left part
Sort the right part

Merge these two parts into one sorted end if


For example: Suppose we have an array(a) with 8 element
25 57 48 37 12 92 86 33
Sorting through merge sort
1 Divide array in two parts
beg mid end
25 57 48 37 12 92 86 33

Left array right array

2 Again divide
[Beg] left array [end] [beg] right array [end]
25 57 48 37 12 92 86 33

beg end beg end beg end beg end


25 57 48 37 12 92 86 33

3 Now finally

25 57 37 48 12 92 33 86
[25] [57] [48] [37] [12] [92] [86] [33]
4 Merge these array with sorting
Left array Right Array
25 57 37 48 12 92 33 86

5 merge them:

 Vidhya Institute of Information Technology 


177
Ideal ‘Data Structure’

25 37 48 57 12 33 86 92

6 Merge them:

12 25 33 37 48 57 86 92
“Now it is finally sorted array”
 Now basically two function require in merge sort :=>
1. For divide list in two parts again & again.
2. For merging these array which are divided by (1) among with sorting concept
then merge them into single one
 Because of these reason we will create two functions:
merge sort () :>
It will divide array in two half (parts)
merge array () ->
It will merge array.

Prototype of these functions


1 merge sort (array, start index, end index);
 Represent the array which we want to sort.
 Start index: -
It specifies the starting index of array.
 End index: -
It specifies the ending index of array
2 Merge array (int array, int la, int ua, intlb, int ub );

Here
la = lower index of array list
ua = upper index of first array
lb = lower index of second array
lb = upper index of second array

Here first array & second array both are same only we divide into two parts for
sorting purpose and represent both with different index.
Practical implementation of Merge Sort:
#include<conio.h>
#include<stdio.h>
#include<process.h>
void mergesort (int [ ], int , int);
void mergearray (int[ ], int, int, int, int, ) ;
void main()
{
int a[10],n,I;
clrscr();
printf(“/n how many element -:”);
scanf(“%d,”&n);
if (n>10)
{
printf(“/n size out of array ”);
getch();
exit();

 Vidhya Institute of Information Technology 


178
Ideal ‘Data Structure’

}
printf(“/n enter %d elements in array “,n) ;
for(i=0; i<n; i++)
{
printf(“/n enter [%d] location element -:”);
scanf(“%d”, &a[i]);
}
void merge array (int a[10],int la, int ua, int lb,int ub)
{
int a[10], i,j,k=0;
i = la;
j = lb;
while ((i<=ua) &&(j<=ub))
{
if (a[i]>a[j])
a[k++] = a[j++];
else if (a[i] <a[j])
a[k++] = a[i++];
}
if (i==ua && j!= ub)
{
while (j<=ub)
a[k++] = a[j++];
}
if (j==ub && i!= ua )
{
while (i<=ua )
a[k++] = a[i++];
}
/* sorted array is sorted in c but we want in a, so we again copy c into a, so we
can get
Sorted array in a */
for (i=0; i<k; i++)
a[i] = c[i];
}
printf(“/n elements before sorting ”);
for (i=0; i<n; i++)
{
printf(“/n %d”, a[i]);
}
/* calling of function which will sort array */
Merge sort (a, 0, n-1);
printf(“/n elements after sorting”);
for (i+0; i<n; i++)
printf(“/n %d”a[i]);
getch();
}
/* function definition */
void merge sort (int a[10], int beg, int end)
{
int mid ;

 Vidhya Institute of Information Technology 


179
Ideal ‘Data Structure’

if (beg<end)
{
mid =(beg +end)/2 ;
merge sort (a,beg, mid); // merge left
merge sort (a, mid+1, end); // merge right
merge array (a,beg, mid, mid+1, end);
/ / it merge left & right with sorting
}
}
QUICK SORT
Quick sort is also a sorting technique like merge sort.
It is also based on “divide and conquer” technique.
This technique finds the element called “pivot” that partitions the array into two values in such a
way that the left sub array are less than elements in the right sub array and greater than the
partitioning element. Then these two sub arrays are sorted respectively.
 It is a “recursive procedure”
The main task in quick sort is to find the element that partitions the array into two
halves and to place it at its proper location in the array.
 Generally the procedure places the first element in the array at its final location.
Use the following steps to perform quick sort:
 Set the index of the first element of the array to loc and left variable and index of the last
element of the array to right variable.
 Begin with the element pointed to by right the array is scanned from right to left
comparison each element with the element pointed by loc.
 If element smaller than the element pointed to by loc is found then element are swapped
(interchanged) and procedure continue with step2.
 If the value of right variable becomes equal to the value of loc the procedure is
terminated .This condition indicates that element is placed in its final position that is loc.
 Begin with the element pointed to by left the array is scanned from left to right
comparing each element on the way with the element pointed to by loc.
 If element greater than the element pointed to by loc is found in this condition, the
elements are interchanged and procedure continue with step 1.
 If the value of the left variable becomes equal to the value of loc. The procedure
terminate here this condition indicates that the element is placed in its final position loc.
 As this procedure terminates, the first element pivot of original the array will be placed
at loc. Its final location in the stored array.
 The element to left of it will be less than this element and element to its right will be
greater than this element.

For e.g.
28,12, 32,17, 22, 30
Initially loc = 0, left = 0, right = 5
Scanning from right to left
28 12 32 17 22 30
| |
Loc/left right

 Vidhya Institute of Information Technology 


180
Ideal ‘Data Structure’

 a[loc] <a [right], true then right----------


28 12 32 17 22 30
| |
loc/left right

 a[loc] <a[right] , false then swap then

22 12 32 17 28 30
| |
left loc/ right
 Scan from left to right
a[loc] >a[left], true then left ++

22 12 32 17 28 30
| │
left loc/right

 a[loc] >a[left], true then left ++

22 12 32 17 28 30
| |
left loc/ right

 a[loc]>a[left], false the swap this values


22 12 28 17 32 30
| |
loc/left right

 Scan from right to left

a[loc]<a [right], true then right--------


22 12 28 17 32 30
| |
loc/left right

 a[loc] >a[right], false then swap


22 12 17 28 32 30
| |
left loc/right

 Scan from left to right


a[loc]>a[left], true left ++
22 12 17 28 32 30
|
loc/left/ right

 Vidhya Institute of Information Technology 


181
Ideal ‘Data Structure’

Now left become equal to loc, so procedure will become terminate here because 28 is
placed at it final position and it divide the array into two sub arrays like this :
22 12 17 28 32 30

[Left sub array] [Right sub array]


o Now we can see that 28 has its final location in the left sub array of 28, all are
less value and in right all are greater.
o After this with the same procedure left array and right sub array will sort one by
one.
o When each element will be at its pivot location then entire array will become
sort.
 Two procedures are required:
One for partition array, pivot location second for left sub and right
sub array.

Implementation of quick sort:


#include<stdio.h>
#include<conio.h>
#define max 100
void quicksort (int [],int,int);
void partition (int[], int, int , int ,int);
void main()
{
int n, I,a[max];
clrscr();
printf(“\n enter how many element ”);
scanf (“%d”, &n);
if (n>max)
{
printf(“\n size out of array”);
getch();
exist(0);
}
printf(“\n enter array element”);
for (i=0; i<n; I++)
{
printf(“\n enter element ”);
scanf(“%d”, &a[i]);
}
clrscr();
printF(“\n element before sorting”);
for (i=0; i<n;i++)
printf(“\n%d”, a[i]);
quick sort (a,o,n-1);
printf(“\n \n element after sorting”);
for (i=0; i<n; i++)
printf(“\n %d”,a[i]);
getch();
}
void quick sort (int a[], int lb, int ub)

 Vidhya Institute of Information Technology 


182
Ideal ‘Data Structure’

{
int loc;
if (lb<ub)
{
partition (a, lb, ub, &loc);
quick sort (a, lb, loc-1);
quick sort (a , loc+1, ub);
}
}
void partition (int a[], int beg, int end,int *loc)
{
int left , right, temp;
int d = 1;
loc = left = beg;
right = end;
while (d= = 1)
{
while ((a[*loc]<=a [right])&&(*loc!= right))
right--;
if (* loc = = right)
d = 0;
else if (a[* loc]> a[right])
{
temp = a[* loc];
a[* loc] = a[right];
a[right] = temp;
*loc = right;
}
if (d==1)
{
while ((a[*loc] > = a[left]) && (*loc! = left))
left ++;
if (*loc = = left)
d = 0;
else if (a[*loc]<a [left])
{
temp = a[*loc];
a[*loc] = a[left];
a[left] = temp;
* loc = left;
}
}
}
Complexity of quick sort: -
o Here array is divided into two values again and again so here complexity is:
 (log 2 n)
o Here each value examined in linear form that’ why here complexity is:
 o(n)
o So total complexity is:
 (n log2 n)
o The efficiency of quick sort is affected by the initial order of elements.

 Vidhya Institute of Information Technology 


183
Ideal ‘Data Structure’

HEAP
A heap is a special type of tree which maintains following these two properties:
1 Shape property
2 Order property

1. Shape property: -
It refers that tree must be a complete binary tree (CBT). CBT is a
binary tree that contains the maximum numbers of nodes possible at least level for its
height that is 2h11 where h = height of a tree.
2. Order property: -
It is also based on two concept means tree must be either:
1 Min heap
2 Max heap

1 Max heap: -

The value stored in every node must be


either less than or equal to the value in
each of its children (direct) called max
heap.
Shape and order, both properties are
maintained here.

2 Min heap: -

The value stored in every node in a tree must


be either greater then or equal to the value in
each of its children is called min heap.

Shape and order, both properties are also maintained here.

Special point: -
A heap is represented in memory using Linear Array, means Sequential
Representation, because heap is a complete binary tree. Therefore a heap of size n is represented
in memory using a linear array of size n.

Operations on Heap: -

There are two basic operations on heap

 Vidhya Institute of Information Technology 


184
Ideal ‘Data Structure’

1. Inserting a new element


2. Deleting an element

1 Inserting a New Element: -

“Element is always inserted at last child of the Heap, means always element will be
inserted at last location of heap.
 This insertion violate (break) heap order property (min heap or max heap) so to maintain
it, we have to readjust the structure of heap so again it becomes tree.
To maintain its order property the new element has to move up from the last
position until it does not reach at its required location.
This operation is called “Reheapify Ppward” operation
Heapify because heap is created.
Reheapfy because is created again.
Upward because element is moving up.

Step:
If the value of last new inserted node is greater than its parent then exchange it with
value of its parent.

Then repeat this same process from the parent node and so on until the order property
is satisfied.
 Basically it is a “recursive procedure”

E.g. consider following heap that is max. 50

40 30

20 10 4 5

Suppose we want insert 45 with in this tree then heap will become like this:
5
0

4 3
0 0

2 1 4 5
0 0

4
5

 Vidhya Institute of Information Technology 


185
Ideal ‘Data Structure’

Here shape property is maintained but order property is not satisfied. So we will use reheapify
upward operation :

(a) compare 5
0 5
0
4 3
0 0 4 3
Exchange 0 0

2 1 4 5
0 0 4 1 4 5
5 0

4
5 2
(b) compare 0

5
0 5
0
4 3
0 0 4 3
Exchange 5 0

4 1 4 5
5 0 4 1 4 5
0 0
2
0 2
0
5 5
0 0
No Exchange
4 3 4 3
5 0 5 0

4 1 4 5 4 1 4 5
0 0 0 0

2 2
0 0

Now finally after reheapify operation, properties are maintained, order also and shape also. In
this way insertion is performed shape also.

 Vidhya Institute of Information Technology 


186
Ideal ‘Data Structure’

Pratical Procedures:
void insert element (int a [], int *n , int value)
{
(*n) ++;
a[*n -1] = value ;
reheapity upward (a, *n-1);
]
Heap a. maintain heap
n , maintain location
Value is mew inserted value * is used with n because of call by values.

Reheapity Upward Procedure:


void reheapityup (int a[], int start)
{
int temp, parent;
if (start >1)
{
parent = start /2;
if (a[parent] <a[start])
{
temp = a[parent];
a[parent ] = a[start];
a[start] = temp;
reheapityup (a, parent);
}
}
}
Following step are performed with in these above two procedures:
1. Increase the size of heap by one (n++)
2. Insert element at last of heap.
a[n-1] = value
3. Apply reheapify upward operation from last node.
(reheapifyup ( ) function is called).
Deleting an Element
“Element is always deleted from the root of the heap”
Required element can not be deleted directly.
When we delete the element from the root of a heap, then it will become vacant space
(empty). So to fill this space, always last element is used.
The last element is placed at the root. This operation again break order property of heap
because in max heap small value (last) is placed at root and in min heap largest value is
placed at root, in both case order property is violate.
So again we have to readjust the entire tree, to satisfy the order property.
To readjust the heap:
The element is move down from the root to its particular location until order property is
not satisfied.
That operation is called “reheapify downward operation” because the element is moving
down.

The reheapify downward works as follows:


Interchange the value of root node with the value of child which is the largest
among its children repeats this step to last node of heap.

 Vidhya Institute of Information Technology 


187
Ideal ‘Data Structure’

5
0

4 3
0 0

2 1 4 5
0 0

If deletion is performed then 50 is removed and its location filled by 5.

5
0

4 3
0 0

2 1 4
0 0
[Remove last node] but order property is not maintained.
40 is interchange with 5, because it is max heap and at root always highest value is placed.
4 4
0 0

5 3 2 3
0 0 0

2 1 4 5 1 4
0 0 0

Now it is final heap after deleting 50 nodes and here order and shape both properties are
maintained

Practical procedure for deleting element:

int delete element (int a[], int *n)


{
int temp = a[i];
a[1] = a[*n]
(*n) --;
reheapify down (a, I, *n);
return temp ;
}

 Vidhya Institute of Information Technology 


188
Ideal ‘Data Structure’

void reheapifydown (int a[], int start, int end)


{
int index , lchild , rchild, max , temp;
lchild = 2* start;
rchild = lchild +1;
if (lchild < = end)
{
max = a[lchild];
index = lchild;
if (rchild < = end)
{
if (a[rchild] >max)
{
max = a[rchild];
index = rchild;
}
}
if (a[start]<a[index])
{
temp = a[start];
a[start]= a[index];
a[index]= temp;
reheapify down (a, index, end);
}
}
}

Following step are performed by using these above two procedures.


 Assign the value of root node to the temp variable.
 Place the last element of heap the root node.
 Reduce the size of heap by one (*n) - -
 Apply reheapify down from root node.
So by using this step element is deleted from the heap and again by using reheapify
downward and upward heap order property is maintained.

Heap sort: -
As we known heap has order property, the min heap or non heap.
Min heap  Minimum value of root node.
Max heap  Maximum value at root node.
We can take the advantage of this condition by using a heap an array of n element can by
easily sorted.
Min heap is used for
“Descending order”
Max heap is used for
“Ascending order”
Following steps are used:
1. Create initial max heap by given elements.
2. Interchange the root value with last element.
3. Use reheapifydown operation from the root to last -1 and recreate heap again.
4. Repeat a step 1 and 2 until there are no more elements to perform reheapify downward
operation.

 Vidhya Institute of Information Technology 


189
Ideal ‘Data Structure’

E.g. sort the following values using:


Heap sort:
5, 3, 45, 10, 9 ,30, 50:
 Create max heap with above values.
 Here (RU) is used for reheapfy upward operation:

 Insert : 45
5 45
RU

3 45 3 5

 Insert: 10
4 4
5 RU 5

3 5 1 5
0

1
0 3
45

 insert : 9

10 5

3 9
 insert : 30 45 45

RU

10 5 10 30

3 9 30 3 9 5

 Vidhya Institute of Information Technology 


190
Ideal ‘Data Structure’

 insert : 50
45 45

RU

10 30 10 50

3 9 5 50 3 9 5 30

50

10 45

3 9 5 30

Now after reheapify operation elements in array are = (level order traversal)

50 10 45 3 9 5 30

Swap first and last


30 10 45 3 9 5 50

 Again create heap with all values expect 50


30, 10, 45, 3, 9, 5,
45 45
30

10 30 10 30
10 45

Now array is 3 9 5

45 10 30 3 9 5 50
Interchange

5 10 30 3 9 45 50

 Vidhya Institute of Information Technology 


191
Ideal ‘Data Structure’

 Again create heap with

5,10,30,3,9

5 10 30

RU RU
10  5 30  5 10

3 9
30

9 10

3 5

Now array is:


30 9 10 3 5 45 50

Swap
5 9 10 3 30 45 50

Create heap with 5, 9, 10, 3

5 9 9 1
0
RU

9 5 5 1 5 9
0
Now array is:
3
10 5 9 3 30 45 50
Swap

3 5 9 10 30 45 50

 Vidhya Institute of Information Technology 


192
Ideal ‘Data Structure’

Create heap with 3, 5, 9

3 5 5 9
RU RU
  

5 3 3 9 3 5

Now array is :

9 3 5 10 30 45 50
swap

5 3 9 10 30 45 50

Create heap with 5, 3

Now array is
5 3 9 10 30 45 50
3
swap

Now array is:


'
3 5 9 10 30 45 50

Finally we can see that array has sorted in ascending order.


For descending order use min heap in this way heap help in sorting the elements.

Implemention of Heap Sort.


#include<stdio.h>
#include<conio.h>
#include<process.h>
#define max 100
void heap sort (int [], int);
void reheapify down(int[], int, int);
void heapify (int[], int);
void main ()
{
int n, I, a[max];
clrscr();
printf(“\n enter how many elements”);
scanf(“%d”, &n);
if (n>max)

 Vidhya Institute of Information Technology 


193
Ideal ‘Data Structure’

{
printf(“\n size out of array”);
getch();
exit(0);
}
printf(“\n enter element in array”);
for (i=1; i<=n; I++)
{
printf(“\n enter elements ”);
scanf(“%d”, &a[i]);
}
printf(“\n elements before sorting”);
for (i=1; i<=n; i++)
printf(“\n %d”, a[i]);
Heap sort (a, n);

printf(“\n \n elements after sorting”);


for (i=0; i<n; I++)
printf(“\m %d”, a[i]);
getch();
}
void heapsort (int a[], int n)
{
int I, temp;
heapify (a,n);
for (i=n; i>1; i--)
{
temp = a[1];
a[1] = a[i];
a[i] = temp;
reheapify down (a, 1, i-1);
}
}
void reheapify down (int a[], int start)
{ int end
int index, lchild,rchild, max , temp;
lchild = 2 start;
rchild = lchild +1;
if (lchild <= end)
{
max = a[lchild];
index = lchild;
if (rchild <= end)
{
if (a[rchild]> max)
{
max = a[rchild];
index = rchild;
}
}
if (a[start] < a[index])

 Vidhya Institute of Information Technology 


194
Ideal ‘Data Structure’

{
temp = a [start]
a[start ] = a[index];
a[index ] = temp;
reheapify down (a,index, end);
}
}
}
viod heapify (int a[], int n)
{
int I, index;
index = n/2 ;

for (i= index ; i>=1; i--)


reheapify down (a, I,n);
}

Complexity of heap sort methodology is


[o (n log2 n)]
 The efficiency of heap sort is not effected by the initial order of elements
 Complexity of reheapifydown is
o (log2n)

HASHING

In all the search algorithms considered so far, the location of the item is determined by a sequence of comparisons. In
each case, a data item sought is repeatedly compared with items in certain locations of the data structure. However, the number
of actual comparison depends on the data structure and the search algorithm used. For example :
 In an array and linked list, the linear search requires O(n) comparisons.
 In a sorted array, the binary search requires 0 (log2n) comparisons.
 In a binary search tree, search requires 0 (log2n) comparisons.

However, there are some applications that require search to be performed in constant time, i.e. O (1) Ideally, it may
not be possible, but still we can achieve a performance very close to it And this is possible using a data structure known as hash
table
A hash table, in basic sense, is a generalization of the simpler notion of an ordinary array. Directly addressing into
array makes it possible to access any data element of the array in O(1) time For example if a[1..200] is an. ordinary array, then
the nth data element, 1<=n<= 100, can be directly accessed as a[n]. However direct addressing is applicable only when we can
allocate an array that has one position for every possible key In addition direct addressing suffers from following problems
1. If the total number of possible keys is very large, it may not be possible to allocate an array of that size because of the
memory available in the system or the applications soft ware does not permit it.
2. If the actually number of keys is very small as compared to total number of possible keys, lot of space in the array will be
wasted.

Therefore, in practice, when the number of keys actually stored is small relative to total number of possible keys, a hash table
becomes more effective since a hash table typically uses an array of size proportional to the number of keys actually stored.
Further, instead of using the key as array index directly, the array index is computed from the key.

HASH TABLE
A hash table is a data structure in which the location of a data item is determined directly as a function of the data
item itself rather than by a sequence of comparisons. Under ideal conditions, the time required to locate a data item in a hash
table is O(1), i.e., it is constant and does not depend on the number of data items stored.
When the set of K of keys stored is much smaller than the universe U of all possible keys, a hash table requires much less
storage space than a direct-address table. In fact, the storage requirements can be reduced to O(k), while maintaining the search
operation an O(1) operation. The difference here is that this bound is for average-case time, whereas for direct addressing it
holds for the worst-case lime.
While in a direct-address table, an element with key k is element is stored in slot h(k); that is, a hash function h is the key
it Here, the hash function h is used to compute the slot from the key k. Here the hash function h maps the universe U of keys
into the slots of a hash table T[0..m-1]. This process of mapping keys to appropriate slots in a hash table is known as hashing.

 Vidhya Institute of Information Technology 


195
Ideal ‘Data Structure’

Above diagram shows the implementing a dynamic set by a hash table T[0..m-1], where the elements are stored in
the table itself. Here each key in the dynamic set K of actual keys is mapped to hash table slots using hash function h. Note that
the keys k2 , k4 and k7 map to the same slot. The mapping of more than one key maps to the same slot is known as collision. We
can also say that the keys k2, k4 and k7 collide. Similarly, key k3, and k5 also collide.
We usually say that an element with key k hashes to slot h(k). We can also say that h (k) is the hash value of key k.
The purpose of the hash function is to reduce the range of array indices that need to be handled. Therefore, instead
of U values, we need to handle only m values which led to the reduction in the storage requirements.
The main flaw of this beautiful idea is that two or more keys (unequal keys) may hash to the same slot, which lead
to the condition called collision. Ideally, it would have been nice if the collision could be avoided by carefully choosing a hash
function. But in practice, it is not possible to avoid collision irrespective of the nature of the hash function Therefore, in these
circumstances, the best solution is to minimize the number of collisions and device a scheme to resolve then collisions if they
occur
The following schemes fat resolving collisions: -
1 Collision resolution by separating chaining
2 Collision resolutions by open addressing

HASH FUNCTION
A hash function h is simply a mathematical formula that manipulates the key in some form to compute the index
for this key in the hash table. For example, a hash function can divide the key by some number, usually the size of the hash table,
and return remainder as the index for the key.
In general, we say that a hash function h maps the universe U of keys into the slots of a hash table T [0...m-1]. This
process of mapping keys to appropriate slots in a hash table is known as hashing.
Different Hash Functions
There is variety of hash functions. The main considerations while choosing a particular hash function h are
1. It should be possible to compute it efficiently.
2. It should distribute the keys uniformly across the hash-table i.e. it should keep the number of collisions as minimum as
possible.

Some popular hash functions are described below.

DIVISION METHOD
In division method, key k to be mapped into one of m slots in the hash-table is divided by m and the remainder of this
division is taken as index into the hash-table.
That is, the hash function
h(k) =k mod m
where mod is the modulus operator and is supported by Pascal language as such. In C/C++ and Java, its equivalent operator
is% character.
The above has function will map the keys in the range 0 to m-1 and is acceptable in C/C++ and Java. But if some
language supports the index from 1 onwards, then the hash function becomes
h(k)= k mod m+1

Example
Consider a hash table with 9 slots i.e. m =9, then the hash function
h(k)= k mod m
will map the key 132 to slot 7 since
h(132)= l32 mod 9 =7
Since it requires only a single division operation, hashing is quite fast. When using the division method, certain values
of m should be avoided. It has been proved in literature that good values form are prime values not too close to exact powers of
2.

 Vidhya Institute of Information Technology 


196
Ideal ‘Data Structure’

MULTIPLICATION METHOD
The multiplication method operates in two steps. In the first step, the key value k is multiplied by a constant A in the
range 0 <A < 1 and extract the fractional part of value kA. In the second step, the fractional value obtained above is multiplied
by m and the floor of the result is taken as the hash value. That is, the hash function is

where “kA mod 1” means the fractional part of kA i e kA — . Note that read as floor of x and represent the largest
integer less than or equal x
Although this method works with any value of A, it works better with some values than others The best choice
depends on the characteristics of the key values Knuth has suggested in his study that the following value of A is likely to work
reasonably well.

Example :
Consider a hash table with 10000 slots i.e. m = 10000, then the hash function

will map the key 123456 to slot 41 since

= 41

MIDSQUARE METHOD
The mid square method also operates in two steps. In the first step, the square of the key value k is taken. In the
second step, the bash value is obtained by deleting digits from ends of the squared value i.e. k 2. It is important to note that same
position of k2 must be used for all keys. Thus, the hash function is
h(k)=s
where s is obtained by deleting digits from both sides of k 2.

Example

Consider a hash table with 100 slots i.e. m=100, and key values k=3205, 7148, 2345

Solution:
The calculations are shown below:

The hash values are obtained by taking fourth and fifth digits counting from right.

FOLDING METHOD
The folding method also operates in two steps in the first step, the key value k is divided into number of parts, k 1, k2,
k3,...,kr where each part has the same number of digits except the last part, which can have 1esser digits. In the second step, these
parts are added together and the hash value is obtained by ignoring the last carry, if any For example if the hash table has 1000
slots, each part will have three digits, and the sum of these parts after ignoring the last carry will also be three-digit number in the
range 0 to 999

Example:

Consider a hash table with 100 slots i.e. m = 100 and key values k= 9235, 714, 71458
Solution:

 Vidhya Institute of Information Technology 


197
Ideal ‘Data Structure’

The calculations are shown below:

In above examples, we have assumed that keys are numeric. However, if the keys are alphanumeric, then the ASCII
codes of fixed number of characters can be added together to transfer the character key to its equivalent numeric key, and then
any of the above hash function can be applied.

 Vidhya Institute of Information Technology 


198
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


199
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


200
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


201
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


202
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


203
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


204
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


205
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


206
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


207
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


208
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


209
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


210
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


211
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


212
Ideal ‘Data Structure’

MEMORY REPRESENTATION OF 2-D ARRAY

 Vidhya Institute of Information Technology 


213
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


214
Ideal ‘Data Structure’

Multidimensional Array

 Vidhya Institute of Information Technology 


215
Ideal ‘Data Structure’

Address Formula

 Vidhya Institute of Information Technology 


216
Ideal ‘Data Structure’

 Vidhya Institute of Information Technology 


217

You might also like