Вы находитесь на странице: 1из 361

Data structure

The logical and mathematical model of a particular organization of


data is called Data structure. The main characteristics of a data
structure are:

Contains component data items which may be atomic or another


data structure

A set of operations on one or more of the component items

Defines rules as to how components relate to each other and to the


structure as a whole
The choice of a particular data structure depends on following
consideration:

It must be rich enough in structure to mirror actual relationships of


data in real world for example the hierarchical relationship of the
entities is best described by the tree data structure.

The structure should be simple enough that one can effecti!ely


process the data when necessary.
The !arious data structures are di!ided into following categories:

Linear data structure- A data structure whose elements form a


se"uence# and e!ery element in structure has a uni"ue predecessor
and a uni"ue successor. $xamples of linear data structure are:

Arrays

Linked Lists

Stacks

Queues

Non-Linear data structures- A data structure whose elements do not


form a se"uence. There is no uni"ue predecessor or uni"ue successor.
$xamples of non linear data structures are trees and graphs.

Linear Data Structures

Arrays% An array is a list of finite number of elements of same data


type. The indi!idual elements of an array are accessed using an index
or indices to the array. &epending on number of indices re"uired to
access an indi!idual element of an array# array can be classified as:

'ne%dimensional array or linear array that re"uires only one


index to access an indi!idual element of an array

Two dimensional array that re"uires two indices to access an


indi!idual element of array

The arrays for which we need two or more indices are (nown
as multidimensional array.

Linked List-

)inear collection of data elements called nodes

$ach node consists of two parts* data part and pointer or lin(
part

+odes are connected by pointer lin(s.

The whole list is accessed !ia a pointer to the first node of the
list

,ubse"uent nodes are accessed !ia the lin(%pointer member of


the current node

)in( pointer in the last node is set to null to mar( the list-s end
.
/se a lin(ed list instead of an array when

0ou ha!e an unpredictable number of data elements 1dynamic


memory allocation possible2

0our list needs to be sorted "uic(ly

&iagram of two data nodes lin(ed together


struct node {
int data;
struct node *nextPtr;
}

nextPtr
.
3oints to an ob4ect of type node
.
5eferred to as a lin(

Ties one node to another node


10 15
NULL pointer 1points to nothing2
&ata member
and pointer

Types of lin(ed lists:


.
,ingly lin(ed list

6egins with a pointer to the first node

Terminates with a null pointer

'nly tra!ersed in one direction


.
Circular# singly lin(ed

3ointer in the last node points bac( to the first node


.
&oubly lin(ed list

Two start pointers . first element and last element

$ach node has a forward pointer and a bac(ward pointer

Allows tra!ersals both forwards and bac(wards


.
Circular# doubly lin(ed list

7orward pointer of the last node points to the first node and
bac(ward pointer of the first node points to the last node
.
8eader )in(ed )ist

)in(ed list contains a header node that contains information


regarding complete lin(ed list.

,tac(s%A stac(# also called last%in%first%out 1)I7'2 system# is a linear


list in which insertions 1push operation2 and deletions 1pop
operations2 can ta(e place only at one end# called the top of stack .
.
,imilar to a pile of dishes
.
6ottom of stac( indicated by a lin( member to NULL
.
Constrained !ersion of a lin(ed list

The two operations on stac( are:


push
.
Adds a new node to the top of the stac(
pop
.
5emo!es a node from the top
.
,tores the popped !alue
.
5eturns true if pop was successful

9ueues% A "ueue# also called a 7irst%in%7irst%out 17I7'2 system# is a


linear list in which insertions can ta(e place at one end of the list#
called the rear of the list and deletions can ta(e place only from other
end # called the front of the list.

,imilar to a supermar(et chec(out line

Insert and remo!e operations

Tree% A tree is a non%linear data structure that represents a hierarchical


relationship between !arious elements. The top node of a tree is called
the root node and each subse"uent node is called the child node of the
root. $ach node can ha!e one or more than one child nodes. A tree
that can ha!e any number of child nodes is called a general tree. If
there is an maximum number + of successors for a node in a tree# then
the tree is called an +%ary tree. In particular a binary 1:%ary2 tree is a
tree in which each node has either ;# <# or : successors.

6inary trees
.
6inary tree can be empty without any node whereas a general tree
cannot be empty.
.
All nodes contain two lin(s

+one# one# or both of which may be +/))


.
The root node is the first node in a tree.
.
$ach lin( in the root node refers to a child
.
A node with no children is called a leaf node
&iagram of a binary tree

B
A D
C

6inary search tree


.
A type of binary treee
.
=alues in left subtree less than parent
.
=alues in right subtree greater than parent
.
7acilitates duplicate elimination
.
7ast searches# maximum of log n comparisons

47
25 77
11 43 65 3
6! 7 17 31 44

>raph% A graph# > # is an ordered set 1=#$2 where = represent set of


elements called nodes or !ertices in graph terminology and $
represent the edges between these elements. This data structure is
used to represent relationship between pairs of elements which are not
necessarily hierarchical in nature. /sually there is no distinguished
?first@ or ?last@ nodes. >raph may or may not ha!e cycles
Algorithms

A finite set of steps that specify a se"uence of operations to be carried


out in order to sol!e a specific problem is called an algorithm
Properties of Algorithms:
<. Finiteness% Algorithm must terminate in finite number of steps
:. Absence of Ambiguity%$ach step must be clear and unambiguous
A. Feasibility%$ach step must be simple enough that it can be easily
translated into the re"uired language
B. nput%These are zero or more !alues which are externally supplied to
the algorithm
C. !utput%At least one !alue is produced
"on#entions $sed for Algorithms

dentifying number%$ach algorithm is assigned as identification


number

"omments%$ach step may contain a comment in brac(ets which


indicate the main purpose of the step

Assignment statement%Assignment statement will use colon%e"ual


notation
.
,et max:D &ATAE<F

nput%!utput% &ata may be input from user by means of a read


statement
.
5ead: =ariable names

,imilarly# messages placed in "uotation mar(s# and data in !ariables


may be output by means of a write statement:
.
Grite: messages or !ariable names

Selection Logic or conditional flo&-


.
If condition# then:
.
Eend of if structureF

Double alternati#e
.
If condition# then
.
$lse:
.
E$nd of if structureF

'ultiple Alternati#es
.
If condition# then:
.
$lse if condition:# then:
.
$lse if conditionA# then
.
$lse:
.
E$nd of if structureF

teration Logic

5epeat% for loop


.
5epeat for (Dr to s by t:
.
E$nd of )oopF

5epeat%Ghile )oop
.
5epeat while condition:
.
E$nd of loopF
Algorithm comple(ity

An algorithm is a se"uence of steps to sol!e a problem. There can be more


than one algorithm to sol!e a particular problem and some of these
solutions may be more efficient than others. The efficiency of an
algorithm is determined in terms of utilization of two resources# time of
e(ecution and memory. This efficiency analysis of an algorithm is called
comple(ity analysis# and it is a !ery important and widely%studied sub4ect
in computer science. 3erformance re"uirements are usually more critical
than memory re"uirements. Thus in general# the algorithms are analyzed
on the basis of performance re"uirements i.e running time efficiency.

,pecifically complexity analysis is used in determining how resource


re"uirements of an algorithm grow in relation to the si)e of input. The
input can be any type of data. The analyst has to decide &hich property
of the input should be measured* the best choice is the property that most
significantly affects the efficiency%factor we are trying to analyze. Host
commonly# we measure one of the following :
.
the number of additions# multiplications etc. 1for numerical
algorithms2.
.
the number of comparisons 1for searching# sorting2
.
the number of data mo!es 1assignment statements2
.
6ased on the type of resource !ariation studied# there are two types of
complexities

Time complexity

,pace complexity
Space "omple(ity% The space complexity of an algorithm is amount of
memory it needs to run to completion. The space needed by a program
consists of following components:

Instruction space%space needed to store the executable !ersion of


program and is fixed.

&ata space%space needed to store all constants# !ariable !alues and


has further two components:
.
,pace re"uired by constants and simple !ariables. This space is
fixed.
.
,pace needed by fixed sized structured !ariable such as arrays and
structures.
.
&ynamically allocated space. This space usually !aries.

$n!ironment stac( space% ,pace needed to store information needed


to resume the suspended functions. $ach time a function is in!o(ed
following information is sa!ed on en!ironment stac(
.
5eturn address i.e from where it has to resume after completion of
the called function
.
=alues of all local !ariables and !alues of formal parameters in
function being in!o(ed.
*ime comple(ity- Time complexity of an algorithm is amount of time it
needs to run to completion. To measure time complexity# (ey
operations are identified in a program and are counted till program
completes its execution. Time ta(en for !arious (ey operations are:

$xecution of one of the following operations ta(es time <:


<. assignment operation
:. single II' operations
A. single 6oolean operations# numeric comparisons
B. single arithmetic operations
C. function return
J. array index operations# pointer dereferences

5unning time of a selection statement 1if# switch2 is the time for the
condition e!aluation K the maximum of the running times for the
indi!idual clauses in the selection.

)oop execution time is the number of times the loop body is


executed K time for the loop chec( and update operations# K time for
the loop setup.
L Always assume that the loop executes the maximum number of
iterations possible

5unning time of a function call is < for setup K the time for any
parameter calculations K the time re"uired for the execution of the
function body.
+(pressing Space and time comple(ity: ,ig -!. notation

It is !ery difficult to practically analyze the !ariation of time


re"uirements of an algorithm with !ariation in size of input. A better
approach to express spaceItime complexity is in the form of a
function f 1n2 where n is the input size for a gi!en instance of
problem being sol!ed.
$fficiency 1algorithm A2 D a function 7 of some property of A@s input.

Ge ha!e to decide which property of the input we are going to


measure* the best choice is the property that most significantly
affects the efficiency%factor we are trying to analyze. 7or example#
the time ta(en to sort a list is in!ariably a function of the length of
the list. The speed of an algorithm !aries with the number of items n.

The most important notation used for expressing this function f1n2 is
,ig ! notation.

6ig ' notation is a characterization scheme that allows to measure the


properties of algorithm such as performance andIor memory
re"uirements in general fashion. big M'- notation

/ses the dominant term of the function

'mits lower order terms and coefficient of dominant


Apart from n 1size of input2# efficiency measure will depend on
three cases which will decide number of operations to be performed.

6est% Case performance under ideal condition

Gorst%case performance under most un fa!orable condition

A!erage case performance under most probable condition.


6ig M'- notation tries to analyze each algorithm performance in
worst condition. It is the rate of increase of f1n2 that is examined as a
measure of efficiency.
/ate of gro&th: ,ig ! notation

,uppose 7 is an algorithm and suppose n is the size of input data. Clearly#


complexity f1n2 of 7 increases as n increases. 5ate of increase of f1n2 is examined
by comparing f1n2 with some standard functions such as log
:
n# n# nlog
:
n# n
:
#n
A
and
:
n.
'ne way to compare f1n2 with these standard functions is to use functional '
notation defined as follows:

Definition: If f1n2 and g1n2 are functions defined on positi!e integers with the
property that f1n2 is bounded by some multiple of g1n2 for almost all n. That is#
suppose there exist a positi!e integer n
o
and a positi!e number H such that for all nN
n
o
we ha!e
Of1n2 O P H Og1n2O

Then we may write


f1n2D' g1n2

Ghich is read as f1n21time ta(en for number of operations2 is of the order of g1n2. If
g1n2Dn# it means that f1n2 is a linear proportional to n. 7or g1n2Dn
:
# f1n2 is
proportional to n
:
. Thus if an array is being sorted using an algorithm with g1n2Dn
:
#
it will ta(e <;; times as long to sort the array that is <; times the size of another
array.

6ased on 6ig ' notation# algorithms can be categorized as

Constant time 1 '1<22 algorithms

)ogarithmic time algorithms 1'1logn22

)inear Time algorithm 1'1n2

3olynomial or "uadratic time algorithm 1'1n


(
22

$xponential time Algorithm 1'1(


n
22
.
It can be seen that logarithmic function log1n2 grows most slowly
whereas (
n
grows most rapidly and polynomial function n
(
grows
in between the two extremities. 6ig-' notation# concerns only the
dominant term# low%order terms and constant coefficients are
ignored in a statement. Thus if g1n2 D n
:
K:n# the !ariation is ta(en
as '1n
:
2 rather than '1n2. Complexities of some well (nown
searching and sorting algorithms is:

)inear ,earch: '1n2 Hergesort: '1nlogn2

6inary ,earch: '1logn2

6ubble sort: '1n


:
2
/$NNN0 *'+

let f1n2 be the function that defines the time an algorithm ta(es for
problem size n. The exact formula for f1n2 is often difficult to get. Ge
4ust need an approximation

Ghat (ind of function is f Q

Is it constantQ linearQ "uadraticQ ....


and# our main concern is large n. 'ther factors may dominate for
small n
"!'PL+1*2 SA'PL+S

assume different algorithms to sol!e a problem

with time functions:T<1n2# T:1n2# TA1n2# TB1n2

plot each for a range of n


10
100 1000
10,000
10
2
10
3
10
4
10
5
10
6
10
7
10
8
n
nlogn
n
2
n
3
2
n
1
Input size n
T
i
m
e

t
a
k
e
n
Rate of Growth of f(n) with n
logn
'ther Asymptotic notations for Complexity Analysis
The big M'- notation defines the upper bound function g1n2 for f1n2
which represents the timeIspace complexity of the algorithm on an
input characteristic n . The other such notations are:

!mega Notation 345- used when function g1n2 defines the lower
bound for function f1n2. It is defined as
Of1n2O R HOg1n2O

*heta Notation 365- /sed when function f1n2 is bounded both from
abo!e and below by the function g1n2. It is defined as
c<Og1n2O P Of1n2O P c:.Og1n2O
Ghere c< and c: are two constants.

Little oh Notation 3o5- According to this notation7


f1n2Do g1n2 iff f1n2 D 'g1n2 and f1n2S Tg1n2

Time%,pace Tradeoff% The best algorithm to sol!e a gi!en problem is


one that re"uires less space in memory and ta(es less time to
complete its execution. 6ut in practice# it is not always possible to
achie!e both of these ob4ecti!es. Thus# we may ha!e to sacrifice one
at the cost of other. This is (nown as *ime-space tradeoff among
algorithms. Thus if space is our constraint# we ha!e to choose an
algorithm that re"uires less space at the cost of more execution time.
'n the other hand# if time is our constraint# such as in real time
systems# we ha!e to choose a program that ta(es less time to complete
execution at the cost of more space.
=arious operations performed on Arrays

*ra#ersal% processing each element in the list

Searching% 7inding location of an element

nsertion% Adding a new element

Deletion% 5emo!ing an element

Sorting%Arranging elements in some type of order

'erging% Combining two lists into a single list

*ra#ersing Linear Arrays- Tra!ersing a linear array is basically#


!isiting each element of array exactly once. Tra!ersing is usually
re"uired to count number of elements of array or to perform other
operations on each element of array. Tra!ersing a linear array depends
on size of array. Thus# tra!ersal is '1n2 operation for an array of size
n.

Algorithm: 3*ra#ersing a linear Array5 8ere )A is a linear array


with lower bound )6 and upper 6ound /6. This algorithm tra!erses
)A applying an operation 35'C$,, to each element of )A

,tep <: EInitialize CounterF ,et (:D)6

,tep :: 5epeat step A and B while (UD/6 5epeat for (D)6 to /6:

,tep A: E=isit $lementF Apply 35'C$,, Apply 35'C$,, to

to )AE(F )AE(F

,tep B: Eincrease CounterF set (:D(K<

E$nd of step : loopF

,tep C: $xit

Insertion and &eletion in an Array% Insertion refers to operation of


adding an element to an array and deletion refers to deleting an
element from an array

Insertion% Insertion can be done at !arious positions but the main


cases underta(en are:
.
Insertion at the start
.
Insertion at the end
.
Insertion in the middle
.
Insertion at any other position
Inserting an element at the end of the array can be done easily
pro!ided the memory space allocated for the array is large enough to
accommodate the additional element.7or inserting at any other
position# elements of array ha!e to be shifted downwards from the
position where insertion is to be done. The new element is then
inserted in !acated position.

Algorithm: 1Inserting into a )inear Array2 NS+/*3LA7N787*+'5


8ere )A is a linear array with + elements and V is a
positi!e integer such that VUD+. This algorithm inserts an
element IT$H into V
th
position in )A.

,tep <: EInitialize counterF ,et W:D+

,tep :: 5epeat steps A and B while W R V:


EHo!e Wth element downwardF ,et )AEWK<F:D)AEWF
E &ecrease CounterF ,et W:DW %<
E$nd of ,tep : )oopF

,tep A: EInsert elementF ,et )AEVF:DIT$H

,tep B:E5eset +F ,et +:D+K<

,tep C: 5eturn

&eletion refers to the operation of remo!ing an element from exiting


list of elements. )i(e insertion# deletion can be done easily from the
end of the list. 8owe!er to delete an element from any other location#
the elements are to be mo!ed upwards in order to fill up the location
!acated by the remo!ed element.
Algorithm: 1&eleting from a )inear Array2 D+L+*+3LA7N787*+'5
8ere )A is a linear array with + elements and V is a
positi!e integer such that VUD+. This algorithm deletes an
element IT$H from V
th
position in )A.

,tep <: EInitialize counterF ,et IT$H:D)AEVF

,tep :: 5epeat for WDV to +%<:


EHo!e WK<st element upwardF ,et )AEWF:D)AEWK<F
E$nd of ,tep : )oopF

,tep A: E5eset +F ,et +:D+K<

,tep B: 5eturn
Analysis of Insertion and deletion operation

The best possible case in insertion operation is when the item is


inserted at the last position. In this case# no mo!ement of elements is
re"uired. The worst case occurs when the element has to be inserted at
the beginning of the list. In this case# we ha!e to mo!e all the
elements down the list. Therefore# the while loop executes n times#
each mo!ing one element down. Thus complexity of insertion
operation is '1n2# i.e linear time.

The best case in deletion occurs when the element to be deleted is the
last element of the array. In this case# no element is mo!ed up. The
worst case occurs when element is deleted from the first position. In
this case# all 1n%<2 elements are mo!ed up. The while loop executes n%
< times# each time mo!ing one element down. Thus complexity of
deletion operation is also '1n2 i.e linear time.

Algorithm: 3Linear Search5 LN+A/3DA*A7 N7 *+'7 L!"5


8ere &ATA is a linear array with + elements and IT$H is a
gi!en item of information. This algorithm finds the location )'C of
IT$H in &ATA# or sets )'C:D; if search is unsuccessful.

,tep <: EInitialize CounterF ,et )'C:D<

,tep :: E,earch for IT$HF


5epeat while )'CUD+:X
If &ATAE)'CF D IT$H# Then:
Grite: -$lement is at the location-# )'C
$xit
E$nd of if structureF
,et )'C:D)'CK<
E$nd of )oopF

,tep A: E/nsuccessfulF If )'CD+K< # then:


,et )'C:D;

,tep B: 5eturn

6inary ,earch: 6inary search is a method of searching in which array


list is di!ided into two e"ual parts.

The main re"uirement of binary search method is that the array has to
be in sorted order.

If the elements of array list are in ascending order# then # if desired


element is less than the middle element of the list# it will ne!er be
present in second half of the array and if desired element is greater
than middle element# it will ne!er be present in first half of the array
list.

Thus focus is gi!en only to the desired half of the array list.

Algorithm: ,NA/23DA*A7 L,7 $,7 *+'7 L!"5


8ere &ATA is a sorted array with lower bound )6 and
upper bound /6# and the IT$H is a gi!en item of
information. The !ariables 6$># $+& and HI&
denote#
beginning# end and middle location of a segment of
elements of &ATA. This algorithm finds the location
)'C
of IT$H in &ATA or set )'CD+/))

,tep <: EInitialize segment !ariableF ,et 6$>:D)6# $+&:D/6


and
HI&:D I+T116$>K$+&2I:2
,tep :: 5epeat while 6$>UD$+& and &ATAEHI&FSIT$H
If IT$H U &ATAEHI&F# then:
,et $+&:D HI& %<
$lse:
,et 6$>:D HI& K<
E$nd of if structureF

,tep A: ,et HI&:DI+T116$>K$+&2I:2


E$nd of step: loopF

,tep B: If &ATAEHI&FDIT$H# then:


,et )'C:DHI&
$lse :
,et )'C:D+/))
E$nd of if structureF

,tep C: 5eturn

Analysis of )inear ,earch and 6inary ,earch

LN+A/ S+A/"9

In best possible case# item may occur at first position. In this case#
search operation terminates in success with 4ust one comparison.
8owe!er# the worst case occurs when either item is present at last
position or element is not there in the array. In former case# search
terminates in success with n comparisons. In latter case# search
terminates in failure with n comparisons. Thus in worst case# the
linear search is '1n2 operation. In a!erage case# the a!erage number
of comparisons re"uired o find the location of item is approximately
e"ual to half of the number of elements in the array.

,NA/2 S+A/"9

In each iteration or in each recursi!e call# search is reduced to one half


of the size of array. Therefore# for n elements# there will be log
:
n
iterations or recursi!e calls. Thus complexity of binary search is
'1log
:
n2. This complexity will be same irrespecti!e of position of
element# e!en if it is not present in array.
Sorting *echni:ues in Array

6ubble sort method% The bubble sort method re"uires n%< passes to
sort an array where n is the size of array. In each pass# e!ery element
of the array aEiF is compared with aEiK<F for iD; to n%( where ( is the
pass number. If aEiFNaEiK<F# they are swapped. This will cause largest
element to mo!e or bubble up.

Algorithm: ,$,,L+3DA*A7 N5
8ere &ATA is an array with + elements. This
algorithm sorts the elements in &ATA.

,tep <: 5epeat step : and A for VD< to +%<:

,tep :: EInitialize pass pointer 3T5F ,et 3T5:D<

,tep A:E$xecute 3assF 5epeat while 3T5 P +%V

I7 &ATAE3T5F N &ATAE3T5 K <F# then:


Interchange &ATAE3T5F and &ATAE3T5 K <F
E$nd of If structureF
,et 3T5:D3T5 K<
E$nd of ,tep A loopF
E$nd of ,tep < )oopF

,tep B: 5eturn

Complexity analysis of 6ubble sort method: Traditionally# time for


sorting an array is measured in terms of number of comparisons. The
number f1n2 of comparisons in bubble sort is easily computed.
,pecifically# there are n%< comparisons during first pass# n%:
comparisons in second pass and so on.
Thus# f1n2D1n%<2 K1n%:2 K%%%%%%%K:K<
D n1n%<2I: D n
:
I : . nI:
D '1n
:
2
Thus time re"uired to sort an array using bubble sort method is
proportional to n
:
where n is number of input items. Thus complexity
of bubble sort is '1n
:
2

,election sort method: ,election sort method re"uires n%< passes to


sort an array. In first pass# find smallest element from elements
aE;F#aE<F#%%%aEn%<F and swap with first element. i.e aE;F. In second
pass# find the smallest element from aE<F#aE:F%%%%%%%%%%aEn%<F and swap
with aE<F and so on.

Algorithm: 1,election sort2 ,$)$CTI'+1A# +2


This algorithm sorts an array A with + elements.

,tep <: 5epeat steps : and A for (D< to +%<

,tep :: ,et Hin:DAE(F and )'C:D(

,tep A: 5epeat for 4D(K< to +:


If HinNAE4F# then:
,et Hin:D AE4F and )'C:DW
E$nd of if structureF
E$nd of step A )oopF

,tep B: EInterchange AE(F and AE)'CFF


,et Temp:D AE(F
,et AE(F:D AE)'CF
,et AE)'CF:DTemp
E$nd of step < )oopF

,tep C 5eturn

Complexity of ,election sort method: The number f 1n2 of


comparisons in selection sort algorithm is independent of original
order of elements. There are n%< comparisons during pass < to find the
smallest element# n%: comparisons during pass : to find the second
smallest element# and so on.

Accordingly#

f 1n2D 1n%<2K1n%:2K%%%%%%%%%%%%%%%%%%%%%%K:K<

D n1n%<2I:D '1n
:
2

The f 1n2 holds the same !alue '1n


:
2 both for worst case and a!erage
case.

Insertion sort% In this procedure of sorting# we pic( up a !alue and


insert it at appropriate place in sorted sub list i.e during (th operation
or iteration# the element aE(F is inserted in its proper place in sorted
sub array aE<F#aE:F#aEAF%%%aE(%<F. This tas( is accomplished by
comparing a E(F with aE(%<F#aE(%:F %%%%%%% and so on until the first
element a E4F such that a E4F P a E(F is found. Then each element
aE(%<F#aE(%:F%%%%%%%%aE4K<F are mo!ed one position up and a E(F is
inserted in 1 4K<2th position in array.
Algorithm: 1Insertion sort2 NS+/*!NS!/*3A 7 N5
This algorithm sorts the array A with + elements.

,tep <: ,et AE;F:D %Y

,tep :: 5epeat steps A to C for VD: to +:

,tep A: ,et T$H3:DAEVF and 3T5:DV%<

,tep B: 5epeat while T$H3 UAE3T5F :


EHo!es element forwardF ,et AE3T5 K <F:DAE3T5F
,et 3T5:D 3T5 . <
E$nd of step B )oopF

,tep C:EInserts element in proper placeF ,et AE3T5 K <F:D T$H3


E$nd of step : )oopF

,tep J: 5eturn

Complexity of Insertion ,ort


The number f1n2 of comparisons in insertion sort algorithm can be
easily computed . Gorst case occurs when array A is in re!erse order
and inner loop must use n%< comparisons.
f1n2D<K:K%%%%%%%%%%%%%%%%n%<
Dn1n%<2I:D'1n
:
2
In a!erage case# there will be approximately 1n%<2I: comparisons in
inner loop
f1n2D<I:K:I:K%%%%%%%%%%%%%%%1n%<2I:Dn1n%<2IBD'1n
:
2

9uic( ,ort% 9uic( sort is a sorting techni"ue that uses the idea of
di!ide and con"uer. This algorithm finds the element# called pi#ot#
that partitions the array into two hal!es in such a way that the
elements in left sub array are less than and elements in right sub array
are greater than the partitioning element 13i!ot2. Then# these two sub
arrays are sorted separately in the same way by di!iding them further.
The main tas( in "uic( sort is to find the element that partitions the
array into two hal!es and to place it at its proper location in array.
Algorithm: Q$"8S!/*3 A7 N5
This algorithm sorts an array A with + elements. )'G$5 and /33$5 are
the two stac(s maintained for storing the lower and upper indexes of list or sublist

,tep <:EInitializeF ,et T'3:D+/))

,tep ::E3ush boundary !alues of A onto stac(s when A has : or more elementsF
If + N <# then:
,et T'3:D T'3 K <# )'G$5E<F:D< and /33$5E<F:D+

,tep A: 5epeat while T'3S +/))


E3op sub list from stac(sF
,et 6$>:D)'G$5ET'3F# $+&:D/33$5ET'3F and
T'3:DT'3%<

,tep B: Call 9/ICV1A# +# 6$># $+&# )'C2

,tep C: E3ush left sub list onto stac(s when it has : or more elementsF
If 6$> U )'C%<# then :
,et T'3:DT'3K<# )'G$5ET'3F:D6$>#
/33$5ET'3F:D)'C%<
E$nd of If structureF
,tep J: E3ush right sub list onto stac(s when it has : or more elementsF
If )'CK< U $+&# then :
,et T'3:DT'3K<# )'G$5ET'3F:D)'CK<#
/33$5ET'3F:D$+&
E$nd of If structureF
E$nd of ,tep A loopF
,tep Z: 5eturn

Algorithm: 9/ICV1A# +# 6$># $+&# )'C2


8ere A is an array with + elements. 3arameters 6$> and
$+& contain the boundary !alues of the sublist of A to which this
procedure applies. )'C (eeps trac( of the position of the first element
AE6$>F of the sublist during the procedure. The local !ariables )$7T
and 5I>8T will contain the boundary !alues of the list of elements
that ha!e not been scanned.
,tep <: EInitializeF. ,et )$7T:D6$># 5I>8T:D$+& and )'C:D6$>
,tep :: E,can from right to leftF
1a2 5epeat while AE)'CF P AE5I>8TF and )'CS5I>8T:
5I>8T:D5I>8T%<
E$nd of )oopF
1b2 If )'CD5I>8T# then: 5eturn
1c 2 If AE)'CFNAE5I>8TF# then:
1i2 EInterchange AE)'CF and AE5I>8TF F

,et T$H3:DAE)'CF
,et AE)'CF:DAE5I>8TF
,et AE5I>8TF:DT$H3
1ii2 ,et )'C:D5I>8T
1iii2 >o To ,tep A
E$nd of If ,tructureF
,tep A: E,can from left to rightF
1a2 5epeat while AE)$7TFP AE)'CF and )$7TS )'C:
,et )$7T:D)$7TK<
E$nd of )oopF
1b2 If )'CD)$7T# then: 5eturn
1c2 If AE)$7TFNAE)'CF# then
1i2 EInterchange AE)$7TF and AE)'CF F


,et T$H3:DAE)'CF
,et AE)'CF:DAE)$7TF
,et AE)$7TF:DT$H3
1ii2 ,et )'C:D)$7T
1iii2 >o To ,tep :
E$nd of If ,tructureF

Algorithm: Quicksort 3DA*A7 F/S*7 LAS*5


This algorithm sorts the array &ATA with + elements.

,tep <: EInitializationF ,et low:D7I5,T and high :D)A,T and


pi!ot:D &ATAE 1lowKhigh2I: FEHiddle element of arrayF

,tep :: 5epeat while low P high:

,tep A: 5epeat while &ATA ElowF U pi!ot:


,et low:D low K<
E$nd of step A loopF

,tep B: 5epeat while &ATA EhighF N pi!ot:


,et high:D high %<
E$nd of step B loopF

,tep C: If low P high# then:


,et temp:D &ATA ElowF
,et &ATA ElowF:D&ATA EhighF
,et &ATA EhighF:D temp
,et low:D low K<
,et high:D high %<
E$nd of if structureF
E$nd of step : )oopF

,tep J: If first U high# then:


9uic(sort 1&ATA# first# high2
E$nd of if structureF

,tep Z: If low U last# then:


9uic(sort 1&ATA# low# last2
E$nd of if structureF

,tep [: $xit

"omple(ity of Quick sort algorithm- The running time of a sorting


algorithm is determined by number f1n2 of comparisons re"uired to
sort n elements. The "uic( sort algorithm has a worst case running
time of order '1n
:
2 but an a!erage case running time of ' 1n log n2.

The worst case occurs when the list is already sorted. Then the first
element will re"uire n comparisons to recognize that it remains at first
position. The first sublist will be empty but the second sublist will
ha!e n%< elements. Accordingly# second sublist will re"uire n%<
comparisons to recognize that it remains at the second position. And
so on. Thus#

71n2DnK1n%<2K%%%%%%%K:K<Dn1nK<2I:Dn
:
I:K'1n2D'1n
:
2

The complexity n log n of a!erage case comes from the fact that each
reduction step of algorithm produces two sub lists. Accordingly#

5educing the initial list places < element and produces two sublists

5educing two sublists places : elements and produces four sublists

5educing four sublists places B elements and produces eight sublists

5educing eight sublists places [ element and produces sixteen sublists

Thus reduction in (th le!el finds the location of :


(%<
elements. 8ence
there will be approximately log
:
n le!els of reduction steps. 7urther
each le!el uses atmost n comparisons Thus

f1n2Dnlogn
Herging of Arrays

,uppose A is a sorted list with r elements and 6 is a sorted list with s


elements. The operation that combines the element of A and 6 into a
single sorted list C with nDr K s elements is called merging.

Algorithm: Herging 1A# 5#6#,#C2


8ere A and 6 be sorted arrays with 5 and , elements
respecti!ely. This algorithm merges A and 6 into an array
C with +D5K , elements

,tep <: ,et +A:D<# +6:D< and +C:D<

,tep :: 5epeat while +A P 5 and +6 P ,:


I7 AE+AF P 6E+6F# then:
,et CE+CF:D AE+AF
,et +A:D+A K<
$lse:
,et CE+CF:D 6E+6F
,et +6:D +6 K<
E$nd of If structureF
,et +C:D +C K<
E$nd of )oopF

,tep A: If +A N5# then:


5epeat while +6 P ,:
,et CE+CF:D 6E+6F
,et +6:D +6K<
,et +C :D +C K<
E$nd of )oopF
$lse:
5epeat while +A P 5:
,et CE+CF:D AE+AF
,et +C:D +C K <
,et +A :D +A K<
E$nd of loopF
E$nd of If structureF

,tep B: 5eturn

Complexity of merging: The input consists of the total number nDrKs


elements in A and 6. $ach comparison assigns an element to the array
C# which e!entually has n elements. Accordingly# the number f1n2 of
comparisons cannot exceed n:
f1n2 P n D '1n2

Herge,ort% Herge sort is a sorting techni"ue in which the series is


sub di!ided into smaller arrays till the array is reduced to only two
elements. The smaller arrays are sorted and are recursi!ely combined
to form the complete sorted array list. This is one of the most efficient
sorting algorithm.

Algorithm: Hergesort 1A# 6$>#$+&2

,tep <: If 6$> U $+&# then:


,et HI&:D 16$> K$+&2I:
Call Hergesort 1A# 6$>#HI&2
Call Hergesort 1A# HI&K<# $+&2
Call Herging1 A# 6$># HI&# HI&K<# $+&2
E$nd of If structureF

,tep :: 5eturn

Algorithm: Herging 1A# )6#)5#56#552


This algorithm merges the elements of sub arrays in sorted
form.)6 and 56 are the lower bounds of sub array to be
sorted and )5 and 55 are the upper bounds of the
subarrays respecti!ely

,tep <: ,et +A:D)6# +6:D56 and +C:D)6

,tep :: 5epeat while +A P )5 and +6 P 55:


I7 AE+AF U AE+6F# then:
,et CE+CF:D AE+AF
,et +A:D+A K<
$lse:
,et CE+CF:D AE+6F
,et +6:D +6 K<
E$nd of If structureF
,et +C:D +C K<
E$nd of )oopF

,tep A: If +A N)5# then:


5epeat while +6 P 55:
,et CE+CF:D AE+6F
,et +6:D +6K<
,et +C :D +C K<
E$nd of )oopF
$lse:
5epeat while +A P )5:
,et CE+CF:D AE+AF
,et +C:D +C K <
,et +A :D +A K<
E$nd of loopF
E$nd of If structureF

,tep B:E/pdating the original array with temporary array CF


5epeat for V:D )6 to 55:
,et AEVF:DCEVF
E$nd of )oopF

,tep C: 5eturn

Complexity of Herge%sort Algorithm% In merge sort algorithm# ma4or


wor( is done in the merge procedure# which is an '1n2 operation. The
merge procedure is called from merge sort procedure after the array is
di!ided into two hal!es and each half has been sorted. In each of
recursi!e calls# one for left half and one for right half# the array is
di!ided into hal!es# thus di!iding the array into four segments. At
each le!el# the number of segments double. Therefore# total di!isions
are log
:
n. Horeo!er each pass merges a total of n elements and thus
each pass will re"uire at most n comparisons. 8ence# for both worst
case and a!erage case
f1n2D nlog
:
nD '1nlog
:
n2

The only disad!antage of merge sort is that it uses an extra temporary


array# of the same size as that of input array# to merge the two hal!es.
The elements of temporary array are copied bac( to original array
before next merging.

5adix sort: 5adix sort is a techni"ue which is usually used when large
lists of names are to be sorted alphabetically. /sing this techni"ue#
one can classify the list of names into :J groups. The list is first
sorted on first letter of each name i.e names are arranged in :J classes
where the first class consists of names that begin with alphabet MA-#
the second class consists of those names that begin with alphabet M6-
and so on. &uring second pass each class is alphabetized according to
second letter of the name and so on.

To sort decimal numbers# where radix or base is <;# we need <;


buc(ets. These buc(ets are numbered ;#<#:#A#B#C#J#Z#[#\. /nli(e#
sorting names# decimal numbers are sorted from right to left i.e first
on unit digit# then on tens digit# then on hundredth digit and so on.

Algorithm: /adi( 3A7 N5


This algorithm sorts an array A with + elements

,tep <: 7ind the largest number of the array

,tep :: ,et digitcount:D+umber of digits of the largest number in


gi!en array

,tep A: 5epeat for passD< to digitcount


Initialize buc(ets

,tep B: 5epeat for iD< to n%<


,et digit:D&igit number pass of aEiF
3ut a EiF in buc(et number digit
Increment buc(et count for buc(et numbered digit
E$nd of ,tep B )oopF
Collect all the numbers from buc(ets in order
E$nd of ,tep A loopF

,tep C: 5eturn
Algorithm: 5adix 1A# +2
This algorithms sorts an array A with + elements
,tep <: E7inding )argest +umberF ,et largestDAE;F
5epeat for (D< to +
If A E(FNlargest# then:
largestDAE(F
E$nd of for loopF
,tep ::ECounting the digits of largest numberF
5epeat while largest N ;
digitcount:DdigitcountK<
largest:DlargestI<;
E$nd of loopF
,tep A:E$xecute a passF 5epeat for passD; to digitcount
,tep B:EInitializing the buc(etsF 5epeat for (D; to \
buc(etcountE(F:D;
E$nd of for )oopF
,tep C: 5epeat for iD; to +%<:
digit:D1AEiFIdi!isor2H'& <;
buc(et EdigitF Ebuc(etcountEdigitFKKF:DaEiF
E$nd of for )oopF
,tep J: 5epeat for (D; to <;
,tep Z: 5epeat for WD; to buc(etcountE(F
AEiKKF:Dbuc(etE(FEWF
E$nd 'f ,tep Z )oopF
E$nd of ,tep J )oopF
,et di!isor:Ddi!isor]<;
E$nd of ,tep A loopF
,tep [ 5eturn


5adix ,ort &emo
<A
A;
:[
CJ
AJ
:[
AJ
CJ
<A
A;
CJ
AJ
A;
:[
<A
5adix 6ins ; < : A B C J Z [ \
AJ
A; <A CJ :[

AJ
<A :[ A; CJ
:[
AJ
CJ
<A
A;
<A
A;
:[
CJ
AJ

Hashing-The search time of each algorithm depends on the numer n of elements


in the collection ! of data" #s it possile to design a search of $%1&' that is, one
that has a constant search time, no matter (here the element is located in the
list) #n theor*, this goal is not an impossile dream"
+et,s loo- at an e.ample" /e ha0e a list of emplo*ees of a fairl* small
compan*" 1ach of 100 emplo*ees has an #2 numer in the range 0 ' 33" #f (e
store the elements %emplo*ee records& in the arra*, then each emplo*ee,s #2
numer (ill e an inde. to the arra* element (here this emplo*ee,s record (ill
e stored"

In this case once we (now the I& number of the employee# we can
directly access his record through the array index. There is a one%to%
one correspondence between the element-s (ey and the array index.
8owe!er# in practice# this perfect relationship is not easy to establish
or maintain. 7or example: the same company might use employee-s
fi!e%digit I& number as the primary (ey. In this case# (ey !alues run
from ;;;;; to \\\\\. If we want to use the same techni"ue as abo!e#
we need to set up an array of size <;;#;;;# of which only <;;
elements will be used:
'b!iously it is !ery impractical to waste that much storage in order to
ma(e sure that each employee-s record in a uni"ue and predictable
location.
6ut what if we (eep the array size down to the size that we will
actually be using 1<;; elements2 and use 4ust the last two digits of (ey
to identify each employeeQ 7or example# the employee with the (ey
number CB[ZJ will be stored in the element of the array with index
ZJ. And the employee with the (ey \[ZC\ will be stored in the
element of the array with index C\. +ote that the elements are not
stored according to the value of the (ey as they were in the pre!ious
example. In fact# the record of the employee with the (ey number
CB[ZJ precedes the record of the employee with (ey number \[ZC\#
e!en though the value of its (ey is larger. Horeo!er# we need a way to
con!ert a fi!e%digit (ey number to two%digit array index. Ge need
some function that will do the transformation. /sing this techni"ue we
call the array a 9ash *able and a function is called a 9ash Function.
9ash *able is a data structure in which keys are mapped to array
positions by a hash function. This table can be searched for an item
in '1<2 time using a hash function to form an address from the (ey.
The easiest way to conceptualize a hash table is to thin( of it as an
array. Ghen a program stores an element in the array# the elements
(ey is transformed by a hash function that produces array indexes for
that array.
9ash Function is a function which# when applied to the (ey#
produces an integer which can be used as an address in a hash table.
The intent is that elements will be relati!ely randomly and uniformly
distributed. In the example abo!e the code for the hash function
would loo( li(e this 1assuming TA6)$^,I_$ was defined <;;2:
int hash^function 1int id^num2
`
return 1id^num a TA6)$^,I_$2*
b
Then# for example# to find an element in the table# a program applies
hash function to the element-s (ey# producing the array index at which
the element is stored.
find 1int (ey2
`
int index*
index D hash^function1(ey2* IIfinding the element
b
"ollision
"ollision is a condition resulting when two or more (eys produce the
same hash location.
7or example# we ha!e already stored se!eral employee-s records# and
our table loo(s something li(e this:
,uppose# our next employee-s (ey is CZ[Z\. Then our hash function
will produce array index Z\. 6ut the array element with index Z\
already has a !alue. As the array begins to fill# (eys will ine!itably
produce the same array index when transformed by the hash function.
Ghen more than one element tries to occupy the same array position#
we ha!e a collision;
+ow# another "uestion arises: can-t we generate the hash function that
ne!er produces a collisionQ The answer is that in some cases it is
possible to generate such a function. This is (nown as a perfect hash
function;
Perfect 9ash Function is a function which# when applied to all the
members of the set of items to be stored in a hash table# produces a
uni"ue set of integers within some suitable range. ,uch function
produces no collisions.
0ood 9ash Function minimizes collisions by spreading the elements
uniformly throughout the array.

There is no magic formula for the creation of the hash function. It can
be any mathematical transformation that produces a relati!ely random
and uni"ue distribution of !alues within the address space of the
storage. Although the de!elopment of a hash function is trial and
error# ,ome popular hash functions fre"uently used are:
Di#ision method%Choose a number m larger than the number n of
(eys in V. The number chosen is usually the prime number.The hash
function 8 is defined by:
81(2D(1mod m2 or 81(2D(1mod m2 K <
The second hash function is used when we want hash addresses
should range from < to m rather than ; to m%<.
'ids:uare method- The (ey ( is s"uared. Then the hash function is
defined as
81(2D)
Ghere ) is obtained by deleting digits from both ends of (
:
.
Folding method%The (ey ( is partitioned into parts (
<
#(
:
#(
A
%%%%(
r

where each part except the last part has e"ual number of digits as the
re"uired address.Then the parts are added together# ignoring the last
carry. That is#
81(2D(
<
K(
:
K%%%%%%%%K(r
Ghere the leading digits# if carry# are ignored.
+(ample: Consider the company each of whose J[ employees is
assigned a uni"ue B%digit employee number. ,uppose ) consists of
<;; two%digit addresses:;;#;<#;:cc.\\. Ge apply the abo!e
studied hash functions to each of the following employee numbers:
A:;C# Z<B[# :ABC
3a5 Di#ision 'ethod- Choose a prime number m close to \\# such as \Z.
Then
81A:;C2DB# 81Z<B[2DJZ 81:ABC2D<Z
7or starting the addresses from ;<#
81A:;C2DBK<DC# 81Z<B[2DJZK<DJ[ 81:ABC2D<ZK<D<[
1b2 'ids:uare method%The following calculations are performed:
(: A:;C Z<B[ :ABC
(
:
: <; :Z: ;:C C< ;\A \;B C B\\ ;:C
81(2: Z: \A \\
Folding method- Chopping the (ey ( into two parts and adding
yields the following hash addresses:
81A:;C2DA:K;CDAZ
81Z<B[2DZ<KB[D<\
81:ABC2D:A KBCD J[
"ollision /esolution
The two ways of dealing with collisions are: rehashing and chaining. The
particular way that one chooses depends upon many factors. 'ne important factor is
the ratio of the number n of (eys in V to number m of hash addresses in hash
table.This ratio# =n/m is called the load factor. The efficiency of a hash function
with a collision resolution procedure is measured by the a!erage number of probes
needed to find the location of record with a gi!en (ey (.
/ehashing % 5esol!ing a collision by computing a new hash location 1index2 in the
array.
)inear 3robing is one type of rehash 1getting a new index2 % A !ery simple one. In
case of linear probing# we are loo(ing for an empty spot incrementing the offset by
< e!ery time. Ge explore a se"uence of location until an empty one is found as
follows: index# index K <# index K :# index K A# ...
In the case of linear probing the code for rehash method will loo( li(e this:
int rehash1int index2
`
int new^index*
new^index D 1index K <2 a TA6)$^,I_$*
return new^index*
b
An alternati!e to linear probing is "uadratic probing.
9uadratic 3robing is a different way of rehashing. In the case of
"uadratic probing we are still loo(ing for an empty location. 8owe!er#
instead of incrementing offset by < e!ery time# as in linear probing#
we will increment the offset by <# A# C# Z# ... Ge explore a se"uence of
location until an empty one is found as follows:
index# index K <# index K B# index K \# index K <J# ...
5etrie!ing a !alue.
Ghen it comes to retrie!ing a !alue# the program recomputes the array index and chec(s the (ey of the
element stored at that location. If the desired (ey !alue matches the (ey !alue at that location# then the
element is found. The search time is on the order of <# '1<2 1< comparison per data item2. If the (ey
doesn-t match# then the search function begins a se"uential search of the array that continues until:
the desired element is found
the search encounters an unused position in the array# indicating that the element is not present
the search encounters the index which was produced by the hash function# indicating that the table is full
and the element is not present
In worst case# the search ta(es 1n%<2 comparison# which is on the order of n# '1n2. Gorst case is if the
table is full and the search function goes through the whole array# 1n%<2 elements# e!ery time comparing
the desired (ey !alue with the (ey at the array location. In the worst case element is either found at the
last position before the one that was produced by the hash function or not found at all.
Ad!antages to this approach
All the elements 1or pointer to the elements2 are placed in contiguous storage. This will speed up the
se"uential searches when collisions do occur.

&isad!antages to this approach


As the number of collisions increases# the distance from the array index computed by the hash function
and the actual location of the element increases# increasing search time.
$lement tend to cluster around elements that produce collisions]. As the array fills# there will be gaps of
unused locations.
The hash table has a fixed size. At some point all the elements in the array will be filled. The only
alternati!e at that point is to expand the table# which also means modify the hash function to
accommodate the increased address space.
"ollision /esolution $sing Linked List or "haining-An alternati!e
to using ad4acent storage 1as in array2 is to use lin(ed list . In this case
table is implemented as an array of lin(ed lists. $!ery element of the
table is a pointer to a list. The list will contain all the elements with
the same index produced by the hash function. 7or example# when the
hash function produces (ey Z\# the new node is created and the array
element with index Z\ now points to this node. Ghen another
element-s (ey produces index Z\# the new node will be created and
attached to the first one and so on. The same set of data as in the
pre!ious example will be organized as follows when we use lin(ed list
for handling collisions:

4etrie0ing a 0alue- /hen it comes to retrie0e a 0alue, the hash function is applied to the
desired -e* and the arra* inde. is produced" Then the search function accesses the list
to (hich this arra* element points to" #t compares the desired -e* to the -e* in the first
node" #f it matches, then the element is found" #n this case the search of the element is of
the order of 1, $%1&" #f not, then the function goes through the list comparing the -e*s"
!earch continues until the element is found or the end of the list is detected" #n this case
the search time depends on the length of the list"
5d0antages to this approach
The hash tale si6e is unlimited %or limited onl* * a0ailale storage space&" #n this case
*ou don,t need to e.pand the tale and recreate a hash function"
7ollision handling is simple8 9ust insert colliding records into a list"
2isad0antages to this approach
5s the list of collided elements %collision chains& ecome long, search them for a desired
element egin to ta-e longer and longer"
:sing pointers slo(s the algorithm8 time re;uired is to allocate ne( nodes
LN8+D LS*

Linked List- A lin(ed list or one%way list is a linear collection of data


elements# called nodes # where linear order is gi!en by means of
pointers. $ach node is di!ided into two parts:

The first part contains the information of the element.

,econd part# called the lin(ed field or next pointer field# contains the
address of the next node in the list.
/epresentation of Linked list in memory

)in(ed list is maintained in memory by two linear arrays: NF! and


LN8 such that NF!<8= and LN8<8= contain respecti!ely the
information part and the next pointer field of node of LS*. )I,T also
re"uires a !ariable name such as S*A/* which contains the location
of the beginning of the list and the next pointer denoted by N$LL
which indicates the end of the LS*.
6$& +/H6$5 3ATI$+T
< Vir(
:
A &ean
B Haxwell
C Adams
J
Z )ane
[ >reen
\ ,amuels
<;
<< 7ields
<: +elson
+$dT
Z
<<
<:
A
B
<
;
[
\
5
START

Algorithm: 3*ra#ersing a Linked List5


)et )I,T be a lin(ed list in memory. This algorithm
tra!erses )I,T# applying an operation 35'C$,, to each
element of )I,T. =ariable 3T5 points to the node
currently being processed.

,tep <: ,et 3T5:D ,TA5T

,tep :: 5epeat while 3T5 S +/)):


Apply 35'C$,, to I+7'E3T5F
,et 3T5:D )I+VE3T5F E3T5 now points to next nodeF
E$nd of ,tep : )oopF

,tep A: $xit

Algorithm: S+A/"93 NF!7LN87S*A/*7*+'7L!"5


)I,T is a lin(ed list in memory. This algorithm finds the
location of )'C of the node where IT$H first appears in
)I,T # or sets )'CD+/))

,tep <: ,et 3T5:D,TA5T

,tep :: 5epeat while 3T5S +/))


If IT$H D I+7'E3T5F# then:
,et )'C :D 3T5
5eturn
$lse:
,et 3T5:D )I+VE3T5F
E$nd of If structureF
E$nd of ,tep : )oopF

,tep A: E,earch is unsuccessfulF ,et )'C:D+/))

,tep B: 5eturn

,inary search cannot be applied to linked list as there is no
pro#ision to locate the middle element of LS*; *his property is
one of the main dra&back of using a linked list as a data
structure;
START
IN!"#TR$
%IN&"#TR$
nsertion into a Linked List-

Together with the lin(ed list # a special list is maintained in memory


which consist of unused memory cells.

This list# which has its own pointer# is called the list of a!ailable space
or the free storage list or the free pool.

This list is called the A#ail List. &uring insertion operation# new nodes
are ta(en from this a!ail list which is maintained 4ust li(e normal data
lin(ed list using its own pointer.

,imilar to ,TA5T# A!ail list also has its own start pointer named as
A>AL which stores the address of the first free node of a!ail list.
Vir( Z
J
&ean <<
Haxwell <:
Adams A
;
)ane B
>reen <
,amuels ;
:
7ields [
+elson \
<
:
A
B
C
J
Z
[
\
<;
<<
<:
START
A'AI%
5
10

Insertion in a )in(ed )ist% Algorithms which insert nodes into lin(ed


lists come up in !arious situations. Three main cases to be discussed
are:

Inserting node at the beginning of the )ist

Inserting node after the node with a gi!en location

Inserting node into a sorted list.


7or all algorithms# !ariable *+' contains the new information
to be added to the list. All cases follow some common steps:

Chec(ing to see if free space is a!ailable in A=AI) list. If


A=AI)D+/))# algorithm will print o#erflo&

5emo!ing first node from A=AI) list. /sing !ariable +$G to


(eep trac( of location of new node# this step can be
implemented by the pair of assignments 1in this order2
N+?:@ A>AL and A>AL:@LN8<A>AL=

Copying new information into new node


NF!<N+?=:@*+'
A'AI%
N()
#T1<
START
INS(RTI!N AT TH( *(GINNING ! TH( %IN&(+ %IST
NS+/*N0 A* *9+ ,+0NNN0 !F *9+ LS*

Algorithm: I+,7I5,T 1I+7'# )I+V#,TA5T#A=AI)#IT$H2


This algorithm inserts IT$H as the first node in the list

,tep <: E'=$57)'G QF If A=AI)D+/))# then


Grite: '=$57)'G
5eturn

,tep :: E5emo!e first node from A=AI) list F


,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F.

,tep A: ,et I+7'E+$GF:DIT$H ECopies new data into new nodeF

,tep B: ,et )I+VE+$GF:D ,TA5T


E+ew node now points to original first nodeF

,tep C: ,et ,TA5T:D+$G EChanges ,TA5T so it points to new


nodeF

,tep J: 5eturn
Inserting into sorted )in(ed )ist

,uppose IT$H is to be inserted in a sorted )in(ed list )I,T.


Then IT$H must 6e inserted 6etween +ode A e 6 ,o That
I+7'1A2UIT$HUI+7'162
Tra!ers the list /sing =ariables 3T5 and Comparing IT$H with
I+7'E3T5F at each node. Veep trac( of the location of
preceding node by using 3ointer !ariable ,A=$.
Thus ,A=$ and 3T5 are /pdated by
,A=$ :D 3T5 and 3T5 :D )in(E3T5F
,A=$ 3T5
,TA5T
NS+/*N0 AF*+/ A 0>+N N!D+

Algorithm: I+,)'C1I+7'# )I+V#,TA5T#A=AI)# )'C# IT$H2


This algorithm inserts IT$H so that IT$H follows the
node with location )'C or inserts IT$H as the first node
when )'C D+/))

,tep <: E'=$57)'GF If A=AI)D+/))# then:

Grite: '=$57)'G

5eturn

,tep :: E5emo!e first node from A=AI) listF


,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F

,tep A: ,et I+7'E+$GF:D IT$H ECopies new data into new nodeF

,tep B: If )'CD+/))# then:


,et )I+VE+$GF:D,TA5T and ,TA5T:D+$G
$lse:
,et )I+VE+$GF:D)I+VE)'CF and )I+VE)'CF:D +$G
E$nd of If structureF

,tep C: 5eturn
A'AI%
START
N()
%!,
-.
IT(/

7or insertion in a sorted list# we use two algorithms.

'ne algorithm finds the location of the node

After which the new node has to be inserted.

This algorithm returns the location to main


algorithm which finally do the insertion.
NS+/*N0 N*! A S!/*+D LS*

Algorithm: NSS/*3NF!7LN87S*A/*7A>AL7*+'5

,tep <: CA)) 7I+&A1I+7'#)I+V# ,TA5T#IT$H#)'C2

,tep :: CA)) I+,)'C1I+7'#)I+V#,TA5T#A=AI)#)'C#IT$H2

,tep A: $xit

Algorithm: FNDA3NF!7LN87S*A/*7*+'7L!"5
This algorithm finds the location )'C of the last node in a
sorted list such that I+7'E)'C FUIT$H# or sets
)'CD+/))

,tep <: E)ist $mpty QF If ,TA5TD+/))# then:


,et )'C:D+/))
5eturn
E$nd of If structureF

,tep :: E,pecial caseF If IT$HUI+7'E,TA5TF# then:


,et )'C:D+/))
5eturn
E$nd of If structureF

,tep A: ,et ,A=$:D,TA5T and 3T5:D)I+VE,TA5TF

,tep B: 5epeat while 3T5S+/)):


If IT$HU I+7'E3T5F# then:
,et )'C:D,A=$
5eturn
E$nd of If ,tructureF
,et ,A=$:D3T5 and 3T5:D)I+VE3T5F
E$nd of ,tep B )oopF

,tep C: ,et )'C:D,A=$

,tep J: 5eturn

Algorithm: NSL!"3NF!7 LN87S*A/*7A>AL7 L!"7 *+'5


This algorithm inserts IT$H so that IT$H follows the
node with location )'C or inserts IT$H as the first node
when )'C D+/))

,tep <: E'=$57)'GF If A=AI)D+/))# then:

Grite: '=$57)'G

5eturn

,tep :: E5emo!e first node from A=AI) listF


,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F

,tep A: ,et I+7'E+$GF:D IT$H ECopies new data into new nodeF

,tep B: If )'CD+/))# then:


,et )I+VE+$GF:D,TA5T and ,TA5T:D+$G
$lse:
,et )I+VE+$GF:D)I+VE)'CF and )I+VE)'CF:D +$G
E$nd of If structureF

,tep C: 5eturn
Deletion of a node from a linked list

Case <: &eletion of node following a gi!en node

Algorithm: D+L3NF!7LN87S*A/*7A>AL7L!"7L!"P5
This algorithm deletes node + with location )'C. )'C3
is location of node which precedes + or when + is first
node# )'C3D+/)).

,tep <: If )'CD+/))# then:


Grite: M/+&$57)'G-
$xit

,tep :: If )'C3D+/))# then:


,et ,TA5T:D)I+VE,TA5TF E&eletes first nodeF
$lse:
,et )I+VE)'C3F:D)I+VE)'CF
E$nd of if structureF

,tep A: E5eturn deleted node to A=AI) listF


,et )I+VE)'CF:DA=AI) and
A=AI):D)'C

,tep B: 5eturn
Deleting the node &ith a gi#en item of information
7or deleting with gi!en item of information# we first need to (now the
location of item to be deleted and also the location preceding the item
to be deleted.
7or this# one algorithm will be called from the main algorithm to search
for the two locations.
Two !ariables# ,A=$ and 3T5 will be used to sa!e the location of
preceding and current node at e!ery comparison respecti!ely. 'nce #
locations are found# deletion will be done in main algorithm.

Algorithm: &$)$T$1I+7'# )I+V# ,TA5T# A=AI)# IT$H2

,tep <: CA)) 7I+&61I+7'# )I+V#,TA5T# IT$H# )'C# )'C32

,tep :: If )'CD+/))# then:


Grite: M/nderflow-
$xit

,tep A: If )'C3D+/))# then:


,et ,TA5T:D )I+VE,TA5TF
$lse:
,et )I+VE)'C3F:D)I+VE)'CF
E$nd of if structureF

,tep B: ,et )I+VE)'CF:DA=AI) and A=AI):D)'C

,tep C: 5eturn

Algorithm: FND,3NF!7LN87S*A/*7*+'7L!"7L!"P5
This algorithm finds the location )'C of first node +
which contains IT$H and location )'C3 of node
preceding +. if IT$H does not appear in the list# procedure
sets )'CD+/)) and if IT$H appears in first node# then it
sets )'C3D+/))

,tep <: If ,TA5TD+/))# then:


,et )'C:D+/)) and )'C3:D+/))
5eturn

,tep :: If I+7'E,TA5TFDIT$H# then:


,et )'C:D,TA5T and )'C3:D+/))
5eturn

,tep A: ,et ,A=$:D,TA5T and 3T5:D)I+VE,TA5TF

,tep B: 5epeat while 3T5S+/)):

,tep C: If I+7'E3T5FDIT$H# then:


,et )'C:D3T5 and )'C3:D,A=$
5eturn

,tep J: ,et ,A=$:D3T5 and 3T5:D)I+VE3T5F


E$nd of )oopF

,tep Z:EItem to be deleted not in listF ,et )'C:D+/))

,tep [: 5eturn
"oncatenating t&o linear linked lists

Algorithm: Concatenate1I+7'#)I+V#,TA5T<#,TA5T:2
This algorithm concatenates two lin(ed lists with start
pointers ,TA5T< and ,TA5T:

,tep <: ,et 3T5:D,TA5T<

,tep :: 5epeat while )I+VE3T5FS+/)):


,et 3T5:D)I+VE3T5F
E$nd of ,tep : )oopF

,tep A: ,et )I+VE3T5F:D,TA5T:

,tep B: 5eturn
"ircular Linked List-

A circular lin(ed list is a lin(ed list in which last element or


node of the list points to first node.

The memory declarations for representing the circular lin(ed


lists are the same as for linear lin(ed lists.

All operations performed on linear lin(ed lists can be easily


extended to circular lin(ed lists with following exceptions:

Ghile inserting new node at the end of the list# its next pointer
field is made to point to the first node.

Ghile testing for end of list# we compare the next pointer field
with address of the first node
Circular lin(ed list is usually implemented using header linked
list.

8eader lin(ed list is a lin(ed list which always contains a special

node called the header node# at the beginning of the list.

This header node usually contains !ital information about the lin(ed
list such as number of nodes in lists# whether list is sorted or not etc.
Circular header

This comes from the following two properties of circular header


lin(ed lists:

The null pointer is not used# and hence all pointers contain !alid
addresses

$!ery 1ordinary 2 node has a predecessor# so the first node may not
re"uire a special case.

Algorithm: 3*ra#ersing a circular header linked list5


This algorithm tra!erses a circular header linked list with
,TA5T pointer storing the address of the header node.

,tep <: ,et 3T5:D)I+VE,TA5TF

,tep :: 5epeat while 3T5S,TA5T:


Apply 35'C$,, to I+7'E3T5F
,et 3T5:D)I+VE3T5F
E$nd of )oopF

,tep A: 5eturn
Searching a circular header linked list

Algorithm: ,5C88)1I+7'#)I+V#,TA5T#IT$H#)'C2

This algorithm searches a circular header lin(ed list

,tep <: ,et 3T5:D)I+VE,TA5TF

,tep :: 5epeat while I+7'E3T5FSIT$H and 3T5S,TA5T:


,et 3T5:D)I+VE3T5F
E$nd of )oopF

,tep A: If I+7'E3T5FDIT$H# then:


,et )'C:D3T5
$lse:
,et )'C:D+/))
E$nd of If structureF

,tep B: 5eturn
Deletion from a circular header linked list
Algorithm: &$))'C8)1I+7'#)I+V#,TA5T#A=AI)#IT$H2
This algorithm deletes an item from a circular header
lin(ed list.

,tep <: CA)) 7I+&68)1I+7'#)I+V#,TA5T#IT$H#)'C#)'C32

,tep :: If )'CD+/))# then:


Grite: Mitem not in the list-
$xit

,tep A: ,et )I+VE)'C3F:D)I+VE)'CF E+ode deletedF

,tep B: ,et )I+VE)'CF:DA=AI) and A=AI):D)'C

EHemory retuned to A!ail listF

,tep C: 5eturn
Algorithm: 7I+&68)1+7'#)I+V#,TA5T#IT$H#)'C#)'C32
This algorithm finds the location of the node to be deleted
and the location of the node preceding the node to be
deleted

,tep <: ,et ,A=$:D,TA5T and 3T5:D)I+VE,TA5TF

,tep :: 5epeat while I+7'E3T5FSIT$H and 3T5S,TA5T


,et ,A=$:D3T5 and 3T5:D)I+VE3T5F
E$nd of )oopF

,tep A: If I+7'E3T5FDIT$H# then:


,et )'C:D3T5 and )'C3:D,A=$
$lse:
,et )'C:D+/)) and )'C3:D,A=$
E$nd of If ,tructureF

,tep B: 5eturn
nsertion in a circular header linked list
Algorithm: I+,5T1I+7'#)I+V#,TA5T#A=AI)#IT$H#)'C2
This algorithm inserts item in a circular header lin(ed list
after the location )'C

,tep <:If A=AI)D+/))# then


Grite: M'=$57)'G-
$xit

,tep :: ,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F

,tep A: ,et I+7'E+$GF:DIT$H

,tep B: ,et )I+VE+$GF:D)I+VE)'CF


,et )I+VE)'CF:D+$G

,tep C: 5eturn
nsertion in a sorted circular header linked list
Algorithm: I+,,5T1I+7'#)I+V#,TA5T#A=AI)#IT$H2
This algorithm inserts an element in a sorted circular header
lin(ed list
,tep <: CA)) 7I+&A1I+7'#)I+V#,TA5T#IT$H#)'C2
,tep :: If A=AI)D+/))# then
Grite: M'=$57)'G-
5eturn
,tep A: ,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F
,tep B: ,et I+7'E+$GF:DIT$H
,tep C: ,et )I+VE+$GF:D)I+VE)'CF
,et )I+VE)'CF:D+$G
,tep J: 5eturn
Algorithm: 7I+&A1I+7'#)I+V#IT$H#)'C#,TA5T2
This algorithm finds the location )'C after which to
insert

,tep <: ,et 3T5:D,TA5T

,tep :: ,et ,A=$:D3T5 and 3T5:D)I+VE3T5F

,tep A: 5epeat while 3T5S,TA5T


If I+7'E3T5FNIT$H# then
,et )'C:D,A=$
5eturn
,et ,A=$:D3T5 and 3T5:D)I+VE3T5F
E$nd of )oopF

,tep B: ,et )'C:D,A=$

,tep C: 5eturn

'ne of the most important application of )in(ed )ist is representation


of a polynomial in memory. Although# polynomial can be represented
using a linear lin(ed list but common and preferred way of
representing polynomial is using circular lin(ed list with a header
node.

3olynomial 5epresentation: 8eader lin(ed list are fre"uently used for


maintaining polynomials in memory. The header node plays an
important part in this representation since it is needed to represent the
zero polynomial.

,pecifically# the information part of node is di!ided into two fields


representing respecti!ely# the coefficient and the exponent of
corresponding polynomial term and nodes are lin(ed according to
decreasing degree. )ist pointer !ariable 3')0 points to header node
whose exponent field is assigned a negati!e number# in this case %<.
The array representation of )ist will re"uire three linear arrays as
C'$77# $d3 and )I+V. 7or example:

31x2D :x
[
%Cx
Z
%Ax
:
KB can be represented as:

P!L2
0 -1 2 8 -5 7 -3 2 4 0
,IR,0%AR H(A+(R %IN(&+ %IST R(#R(S(NTATI!N ! 21
.
231
4
231
2
56
H(A+(R N!+( )ITH (7# 2- AN+ ,!( 8

Addition of polynomials using linear


lin(ed list representation for a polynomial
Algorithm:ADDP!L21 "!+FF7 P!?+/7 LN87 P!L2A7 P!L2B7 S$'P!L27 A>AL2
This algorithm adds the two polynomials implemented using linear lin(ed
list and stores the sum in another linear lin(ed list. 3')0< and 3')0: are
the two !ariables that point to the starting nodes of the two polynomials.
,tep <: ,et ,/H3')0:DA=AI) and A=AI):D)I+VEA=AI)F
,tep :: 5epeat while 3')0< S +/)) and 3')0:S+/)):
If 3'G$5E3')0<FN3'G$5E3')0:F#then:
,et C'$77E,/H3')0F:DC'$77E3')0<F
,et 3'G$5E,/H3')0F:D3'G$5E3')0<F
,et 3')0<:D)I+VE3')0<F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F
$lse If 3'G$5E3')0:FN3'G$5E3')0<F# then:
,et C'$77E,/H3')0F:DC'$77E3')0:F
,et 3'G$5E,/H3')0F:D3'G$5E3')0:F
,et 3')0::D)I+VE3')0:F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F

$lse:
,et C'$77E,/H3')0F:DC'$77E3')0<FKC'$77E3')0:F
,et 3'G$5E,/H3')0F:D3'G$5E3')0<F
,et 3')0<:D)I+VE3')0<F
,et 3')0:D)I+VE3')0:F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F
E$nd of If structureF
E$nd of )oopF

,tepA: If 3')0<D+/)) # then:


5epeat while 3')0:S+/))
,et C'$77E,/H3')0F:DC'$77E3')0:F
,et 3'G$5E,/H3')0F:D3'G$5E3')0:F
,et 3')0::D)I+VE3')0:F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F
E$nd of )oopF
E$nd of If ,tructureF



,tep B: If 3')0:D+/))# then:
5epeat while 3')0<S+/))
,et C'$77E,/H3')0F:DC'$77E3')0<F
,et 3'G$5E,/H3')0F:D3'G$5E3')0<F
,et 3')0<:D)I+VE3')0<F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F
E$nd of )oopF
E$nd of If ,tructureF
,tep C: ,et )I+VE,/H3')0F:D+/))
,et ,/H3')0:D)I+VE,/H3')0F
,tep J: 5eturn

Addition of polynomials using circular header


lin(ed list representation for polynomials
Algorithm: ADDP!L21 "!+FF7 P!?+/7 LN87 P!L2A7P!L2B7 S$'P!L27 A>AL2
This algorithm finds the sum of two polynomials implemented using header circular
lin(ed lists. 3')0< and 3')0: contain the addresses of header nodes of two
polynomials and ,/H3')0 is the circular header lin(ed list storing the terms of sum of
two polynomials
,tep <: ,et 8$A&$5:DA=AI) and A=AI):D)I+VEA=AI)F
,tep :: ,et ,/H3')0:D8$A&$5
,et )I+VE,/H3')0 F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F
,tep A: ,et ,TA5T<:D3')0< and ,TA5T::D3')0:
,et 3')0<:D)I+VE,TA5T<F and 3')0::D)I+VE,TA5T:F
,tep B: 5epeat while 3')0< S ,TA5T< and 3')0:S,TA5T::
If 3'G$5E3')0<FN3'G$5E3')0:F#then:
,et C'$77E,/H3')0F:DC'$77E3')0<F
,et 3'G$5E,/H3')0F:D3'G$5E3')0<F
,et 3')0<:D)I+VE3')0<F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F
$lse If 3'G$5E3')0:FN3'G$5E3')0<F# then:
,et C'$77E,/H3')0F:DC'$77E3')0:F
,et 3'G$5E,/H3')0F:D3'G$5E3')0:F
,et 3')0::D)I+VE3')0:F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F

$lse:
,et C'$77E,/H3')0F:DC'$77E3')0<FKC'$77E3')0:F
,et 3'G$5E,/H3')0F:D3'G$5E3')0<F
,et 3')0<:D)I+VE3')0<F
,et 3')0:D)I+VE3')0:F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F
E$nd of If structureF
E$nd of )oopF

,tepC: If 3')0<D,TA5T< # then:


5epeat while 3')0:S ,TA5T:
,et C'$77E,/H3')0F:DC'$77E3')0:F
,et 3'G$5E,/H3')0F:D3'G$5E3')0:F
,et 3')0::D)I+VE3')0:F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F
E$nd of )oopF
E$nd of If ,tructureF



,tep J: If 3')0:D,TA5T:# then:
5epeat while 3')0<S,TA5T<
,et C'$77E,/H3')0F:DC'$77E3')0<F
,et 3'G$5E,/H3')0F:D3'G$5E3')0<F
,et 3')0<:D)I+VE3')0<F
,et )I+VE,/H3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,/H3')0:D)I+VE,/H3')0F
E$nd of )oopF
E$nd of If ,tructureF
,tep Z: ,et )I+VE,/H3')0F:D8$A&$5 and
,/H3')0:D)I+VE,/H3')0F
,tep [: 5eturn

'ultiplication of Polynomials using linear


linked list representation for polynomials
Algorithm: '$LP!L21 "!+FF7 P!?+/7 LN87 P!L2A7 P!L2B7 P/!DP!L27 A>AL5
This algorithm multiplies two polynomials implemented using linear lin(ed
list. 3')0< and 3')0: contain the addresses of starting nodes of two
polynomials. The result of multiplication is stored in another lin(ed list
whose starting node is 35'&3')0
,tep <: ,et 35'&3')0:DA=AI) and A=AI):D)I+VEA=AI)F
,et ,TA5T:D35'&3')0
,tep :: 5epeat while 3')0< S +/))
,tep A:5epeat while 3')0:S+/)):
,et C'$77E35'&3')0F:DC'$77E3')0<F]C'$77E3')0:F
,et 3'G$5E35'&3')0F:D3'G$5E3')0<FK3'G$5E3')0:F
,et 3')0::D)I+VE3')0:F
,et )I+VE35'&3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et 35'&3')0:D)I+VE35'&3')0F
E$nd of step B loopF
,et 3')0<:D)I+VE3')0<F
E$nd of step A loopF
,tep B ,et )I+VE35'&3')0F:D+/)) and 35'&3')0:D)I+VE35'&3')0F
,tep C: 5eturn

Algorithm: '$LP!L21 "!+FF7 P!?+/7 LN87 P!L2A7 P!L2B7 P/!DP!L27 A>AL2
This algorithm finds the product of two polynomials implemented using header
circular lin(ed list. 3')0< and 3')0: contain addresses of header nodes of two
polynomials. The result of multiplication is stored in another header circular lin(ed list.
,tep <: ,et 8$A&$5:DA=AI) and A=AI):D)I+VEA=AI)F
,tep :: ,et 35'&3')0 :D8$A&$5
,et )I+VE35'&3')0 F:DA=AI) and A=AI):D)I+VEA=AI)F
,et 35'&3')0:D)I+VE35'&3')0F
,tep A: ,et ,TA5T<:D3')0< and ,TA5T::D3')0:
,et 3')0<:D)I+VE,TA5T<F and 3')0::D)I+VE,TA5T:F
,tep B: 5epeat while 3')0< S ,TA5T<
,tep C: 5epeat while 3')0:S ,TA5T:
,et C'$77E35'&3')0F:DC'$77E3')0<F]C'$77E3')0:F
,et 3'G$5E35'&3')0F:D3'G$5E3')0<FK3'G$5E3')0:F
,et 3')0::D)I+VE3')0:F
,et )I+VE35'&3')0F:DA=AI) and A=AI):D)I+VEA=AI)F
,et 35'&3')0:D)I+VE35'&3')0F
E$nd of ,tep C )oopF
,et 3')0<:D)I+VE3')0<F
E$nd of ,tep B )oopF
,tep J: ,et )I+VE35'&3')0F:D8$A&$5 and 35'&3')0:D)I+VE35'&3')0F
,tep Z: 5eturn

Doubly Linked List: *&o-&ay List

A two%way list is a linear lin(ed list which can be tra!ersed in two


directions: in usual forward direction from beginning of the list to end
and in bac(ward direction from end of list to the beginning. Thus#
gi!en the location )'C of a node + in list# one has immediate access
to both the next node and the preceding node in the list.

$ach node of a two%way list is di!ided into three parts:


.
An information field I+7' which contains data of +
.
A pointer field 7'5G which contains the location of next node in
the list
.
A pointer field 6ACV which contains the location of preceding
node.
The list also re"uires two list pointer !ariables 7I5,T which
points to first node in the list and )A,T which points to the last node
in the list. Thus null pointer will appear in 7'5G field of last node in
list and also in 6ACV field of first node in list.

Two way lists are maintained in memory by means of linear arrays in


same way as one way list except that two pointer arrays # 7'5G and
6ACV # are re"uired instead of one list pointer !ariable. The list
A=AI) will still be maintained as a one%way list.
IRST
%AST
!R)"#TR$
*A,&"#TR$
!perations on a *&o-&ay list

Tra!ersal

Algorithm: *ra#ersal
This algorithm tra!erses a two%way list. 7'5G and 6ACV
are the two address parts of each node containing the address
of next node and pre!ious node respecti!ely. I+7' is the
information part of each node. ,TA5T contains the address
of the first node
,tep <: ,et 3T5:D,TA5T
,tep :: 5epeat while 3T5S +/))
Apply 35'C$,, to I+7'E3T5F
,tep A: ,et 3T5:D7'5GE3T5F
E$nd of ,tep : )oopF
,tep B: $xit

Algorithm: ,$A5C81I+7'#7'5G#6ACV#IT$H#,TA5T#)'C2
This algorithm searches the location )'C of IT$H in a two%
way list and sets )'CD+/)) if IT$H is not found in the list

,tep <: ,et 3T5:D,TA5T

,tep :: 5epeat while 3T5S+/)) and I+7'E3T5FSIT$H


,et 3T5:D7'5GE3T5F
E$nd of )oopF

,tep A: If I+7'E3T5FDIT$H# then:


,et )'C:D3T5
$lse:
,et )'C:D+/))

,tep B: 5eturn

Algorithm: &$)$T$1I+7'#75'G#6ACV#,TA5T#A=AI)#)'C2
This algorithm deletes a node from a two%way list

,tep <: If )'CD,TA5T # then:


,TA5T:D7'5GE,TA5TF
6ACVE,TA5TF:D+/))
5eturn

,tep :: E&elete nodeF ,et 7'5GE6ACVE)'CFF:D7'5GE)'CF


,et 6ACVE7'5GE)'CFF:D6ACVE)'CF

,tep A: E5eturning node to A=AI)F


,et 7'5GE)'CF:DA=AI) and A=AI):D)'C

,tep B: 5eturn

Algorithm:I+,5T 1I+7'#7'5G#6ACV#,TA5T#A=AI)#)'CA# )'C6# IT$H2


This algorithm inserts an item in a doubly lin(ed list.
)'CA and )'C6 location of ad4acent nodes A and 6

,tep <: E'=$57)'GF If A=AI)D+/))# then:


Grite: '=$57)'G
5eturn

,tep :: ,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F


,et I+7'E+$GF:DIT$H

,tep A: ,et 7'5GE)'CAF:D+$G and 6ACVE+$GF:D)'CA


,et 7'5GE+$GF:D)'C6 and 6ACVE)'C6F:D+$G

,tep B: 5eturn
,A"8<P*/=
!R)"#TR$
N()
*+S* Q$+S*!NS

Algorithm to copy the contents of one lin(ed list to another

Algorithm: Copy 1I+7'#)I+V#,TA5T#A=AI)2


This algorithm copies the contents of one lin(ed list to
another.

,tep <: If A=AI)D+/))#then


Grite: M'!erflow-
5eturn

,tep :: ,et 3T5:D,TA5T

,tep A: ,et +$G:DA=AI) # ,TA5T<:D+$G and A=AI):D)I+VEA=AI)F

,tep B: 5epeat while 3T5S +/))


I+7'E+$GF:DI+7'E3T5F
)I+VE+$GF:DA=AI) and A=AI):D)I+VEA=AI)F
+$G:D)I+VE+$GF
E$nd of )oopF

,tep C: ,et )I+VE+$GF:D+/))

,tep J: 5eturn

Algorithm: Copy 1I+7'#)I+V#,TA5T#,TA5T<2
This algorithm copies the contents of one lin(ed list to another. ,TA5T A+& ,TA5T< are the
start pointers of two lists
,tep <: ,et 3T5:D,TA5T and 3T5<:D,TA5T<
,tep :: 5epeat while 3T5S +/)) and 3T5< S +/))
I+7'E3T5<F:DI+7'E3T5F
3T5<:D)I+VE3T5<F
3T5:D)I+VE3T5F
E$nd of )oopF
,tep A: If 3T5D+/)) and 3T5<D+/))
5eturn
,tep B:ECase when the list to be copied is still leftF
If 3T5<D+/))#then
3T5<: DA=AI) and A=AI):D)I+VEA=AI)F
5epeat while 3T5 S +/))
I+7'E3T5<F:DI+7'E3T5F
)I+VE3T5<F:DA=AI) and A=AI):D)I+VEA=AI)F
3T5<:D)I+VE3T5<F
E$nd of )oopF

,tep C: ECase when list to be copied is finished# Truncate the extra nodesF
If 3T5< S+/))# then
,et 3T5<:D+/))
E$nd of If structureF
,tep J: 5eturn

Algorithm to insert a node after the (


th
node in the circular lin(ed list

Algorithm: I+,5T 1I+7'#)I+V#,TA5T#A=AI)#V#IT$H2


This algorithm inserts in a circular lin(ed list after the (th node

,tep <: If A=AI):D+/))# then


Grite: M'=$57)'G-
5eturn

,tep :: ,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F

,et I+7'E+$GF:DIT$H

,tep A: ,et 3T5:D,TA5T and +:D<

,tep B: If +DV# then


,et )I+VE+$GF:D)I+VE3T5F
,et )I+VE3T5F:D+$G
5eturn

,tep C: ,et 3T5:D)I+VE3T5F and

,tep J: 5epeat while + S V


,et 3T5:D)I+VE3T5F and +:D+K<
E$nd of if structureF

,tep Z: ,et )I+VE+$GF:D)I+VE3T5F


,et )I+VE3T5F:D+$G

,tep [: 5eturn

Algorithm to delete the (


th
node from a doubly lin(ed list

Algorithm: &el 1I+7'#7'5G#6ACV#7I5,T#)A,T#A=AI)#V2


This algorithm deletes the (th node

,tep <: ,et +:D< and 3T5:D7I5,T

,tep :: ,et ,A=$:D3T5 and 3T5:D7'5GE3T5F

,tep A: 5epeat while +S V


,et ,A=$:D3T5 and 3T5:D7'5GE3T5F
,et +:D+K<
E$nd of If structureF

,tep B: If +DV# then


7'5GE,A=$F:D7'5GE3T5F
6ACVE7'5GE3T5FF:D6ACVE3T5F
7'5GE3T5F:DA=AI) and A=AI):D3T5
E$nd of If structureF

,tep C: 5eturn
0A/,A0+
"!LL+"*!N

In computer science# garbage collection 1>C2 is a form of automatic memory


management. The garbage collector# or 4ust collector# attempts to reclaim garbage#
or memory used by ob4ects that will ne!er be accessed or mutated again by the
application. >arbage collection is often portrayed as the opposite of manual
memory management# which re"uires the programmer to specify which ob4ects to
deallocate and return to the memory system.

The basic principle of how a garbage collector wor(s is:

&etermine what data ob4ects in a program will not be accessed in the future

5eclaim the resources used by those ob4ects .


/eachability of an obCect

Informally# a reachable ob4ect can be defined as an ob4ect for which there exists
some !ariable in the program en!ironment that leads to it# either directly or through
references from other reachable ob4ects. Hore precisely# ob4ects can be reachable in
only two ways:

A distinguished set of ob4ects are assumed to be reachablefthese are (nown as the


roots. Typically# these include all the ob4ects referenced from anywhere in the call
stac( 1that is# all local !ariables and parameters in the functions currently being
in!o(ed2# and any global !ariables.

Anything referenced from a reachable ob4ect is itself reachable* more formally#


reachability is a transiti!e closure
.

The memory is traced for garbage collection using *racing collectors


!/ S'PL2 "!LL+"*!/S. Tracing collectors are called that
way because they trace through the wor(ing set of memory. These
garbage collectors perform collection in cycles. A cycle is started
when the collector decides 1or is notified2 that it needs to reclaim
storage# which in particular happens when the system is low on
memory. The original method in!ol!es a nai!e mar(%and%sweep in
which the entire memory set is touched se!eral times

In this method# each ob4ect in memory has a flag 1typically a single


bit2 reser!ed for garbage collection use only. This flag is always
cleared 1counter%intuiti!ely2# except during the collection cycle. The
first stage of collection sweeps the entire @root set@# mar(ing each
accessible ob4ect as being @in%use@. All ob4ects transiti!ely accessible
from the root set are mar(ed# as well. 7inally# each ob4ect in memory
is again examined* those with the in%use flag still cleared are not
reachable by any program or data# and their memory is freed. 17or
ob4ects which are mar(ed in%use# the in%use flag is cleared again#
preparing for the next cycle.2.
'o#ing #s; non-mo#ing garbage "ollection

'nce the unreachable set has been determined# the garbage collector
may simply release the unreachable ob4ects and lea!e e!erything else
as it is# or it may copy some or all of the reachable ob4ects into a new
area of memory# updating all references to those ob4ects as needed.
These are called gnon%mo!ingg and gmo!ingg garbage collectors#
respecti!ely.

At first# a mo!ing garbage collection strategy may seem inefficient


and costly compared to the non%mo!ing approach# since much more
wor( would appear to be re"uired on each cycle. In fact# howe!er# the
mo!ing garbage collection strategy leads to se!eral performance
ad!antages# both during the garbage collection cycle itself and during
actual program execution
'emory Allocation: 0arbage "ollection

The maintenance of lin(ed list in memory assumes the possibility of


inserting new nodes into the lin(ed lists and hence re"uires some
mechanism which pro!ides unused memory space for new nodes..
Analogously# some mechanism is re"uired whereby memory space of
deleted nodes becomes a!ailable for future use.
Together with lin(ed list# a special list is maintained in memory
which consists of unused memory cells. This list# which has its own
pointer is called the list of a!ailable space or the free%storage list or
the free pool. &uring insertions and deletions in a lin(ed list# these
unused memory cells will also be lin(ed together to form a lin(ed list
using A=AI) as its list pointer !ariable.
0arbage "ollection: The operating system of a computer may
periodically collect all deleted space onto the free%storage list. Any
techni"ue which does this collection is called garbage collection.
>arbage collection is mainly used when a node is deleted from a list
or an entire list is deleted from a program.
>arbage collection usually ta(es place in two steps:

7irst the computer runs through the whole list tagging those cells
which are currently in use#

The computer then runs through the memory collecting all untagged
spaces onto the free storage list.
>arbage collection may ta(e place when there is only some
minimum amount of space or no space at all left in free storage list or
when C3/ is idle and has time to do the collection.
S*A"8S

,tac(% A stac( is a linear data structure in which items may be added


or remo!ed only at one end . Accordingly# stac(s are also called last%
in%first%out or )I7' lists. The end at which element is added or
remo!ed is called the top of the stack. Two basic operations
associated with stac(s are :

Push% Term used to denote insertion of an element onto a stac(.

Pop% Term used to describe deletion of an element from a stac(.


The order in which elements are pushed onto a stac( is re!erse of the
order in which elements are popped from a stac(
/epresentation of stacks

,tac(s may be represented in memory in !arious ways usually by


means of one%way list or a linear array
In array representation of stac(# stac( is maintained by an
array named ,TACV # a !ariable T'3 which contains the
locationIindex of top element of stac( and a !ariable HAd,TV
gi!ing the maximum number of elements that can be held by the
stac(. The condition T'3D; or T'3D+/)) indicates that stac( is
empty.
The operation of addition of an item on stac( and operation of
remo!ing an item from a stac( may be implemented respecti!ely by
sub algorithms# called P$S9 and P!P. 6efore executing operation
3/,8 on to a stac(# one must first test whether there is room in the
stac( for the new item. If not# then we ha!e the condition (nown as
o#erflo&; Analogously# in executing the 3'3 operation# one must first
test where there is an element in stac( to be deleted. If not# then we
ha!e condition (nown as underflo&;
A55A0
IH3)$H$+TATI'+
'7 ,TACV

Algorithm: 3/,8 1,TACV#T'3#HAd,TV#IT$H2


This algorithm pushes an item onto the stac( array. T'3
stores the index of top element of the stac( and HAd,TV
stores the maximum size of the stac(.

,tep <: E,tac( already filledF


If T'3DHAd,TV# then:
Grite: M'=$57)'G-
5eturn

,tep :: ,et T'3:DT'3K<

,tep A: ,et ,TACVET'3F:DIT$H

,tep B: 5eturn
Algorithm: 3'31,TACV#T'3#IT$H2
This procedure deletes the top element of
,TACV array and assign it to !ariable IT$H

,tep <: If T'3D;#then:


Grite: M/+&$57)'G-
5eturn

,tep :: ,et IT$H:D,TACVET'3F

,tep A: ,et T'3:DT'3%<

,tep B: 5eturn

A stac( represented using a lin(ed list is also (nown as lin(ed stac(.


The array based representation of stac( suffers from following
limitations:

,ize of stac( must be (nown in ad!ance

5epresenting stac( as an array prohibits the growth of stac( beyond


finite number of elements.
In a lin(ed list implementation of stac(# each memory cell will
contain the data part of the current element of stac( and pointer that
stores the address of its bottom element and the memory cell
containing the bottom most element will ha!e a N$LL pointer
Push operation on linked list representation of stack

Algorithm: 3/,81I+7'# )I+V# T'3# IT$H# A=AI)2


This algorithm pushes an element to the top of the stac(
,tep <: If A=AI)D+/))# then
Grite: M'=$57)'G-
5eturn
,tep :: ,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F
,tep A: ,et I+7'E+$GF:DIT$H
,tep B: If T'3D+/))# then
,et )I+VE+$GF:D+/))
,et T'3:D+$G
5eturn
$lse:
,et )I+VE+$GF:DT'3
,et T'3:D+$G
,tep C: 5eturn
P!P operation on linked list representation of stack

Algorithm: 3'31I+7'# )I+V# T'3# A=AI)2

This algorithm deletes an element from the top of the


stac(

,tep <: If T'3D+/)) # then:


Grite: M/+&$57)')G-
5eturn

,tep :: ,et 3T5:DT'3


,et T'3:D)I+VET'3F
Grite: I+7'E3T5F

,tep A: ,et )I+VE3T5F:DA=AI) and A=AI):D3T5

,tep B: 5eturn
Application of stack

+#aluation of arithmetic e(pression;

7or most common arithmetic operations# operator symbol is placed


between its operands. This is called infi( notation of an expression.
To use stac( to e!aluate an arithmetic expression# we ha!e to con!ert
the expression into its prefix or postfix notation.

Polish notation # refers to the notation in which operator symbol is


placed before its two operands. This is also called prefi( notation of
an arithmetic expression. The fundamental property of polish notation
is that the order in which operations are to be performed is completely
determined by positions of operators and operands in expression.
Accordingly# one ne!er needs parentheses when writing expression in
polish notation.

/e#erse Polish notation refers to notation in which operator is placed


after its two operands. This notation is fre"uently called postfi(
notation. $xamples of three notations are:

I+7Id +'TATI'+: AK6

35$7Id '5 3')I,8 +'TATI'+: KA6

3',T7Id '5 5$=$5,$ 3')I,8 +'ATATI'+: A6K

Con!ert the following infix expressions to prefix and postfix forms

AK16]C2

1AK62I1CK&2

3refix: KA]6C 3ostfix: A 6C]K

3refix: I KA6KC& 3ostfix: A6KC&KI



The computer usually e!aluates an arithmetic expression written in infix
notation in two steps.

Con!erts expression to postfix notation

$!aluates the postfix notation.

+#aluation of postfi( e(pression

,uppose 3 is an arithmetic expression written in postfix notation. The


following algorithm which uses a ,TACV to hold operands and
e!aluates 3

Algorithm: This algorithm finds the =A)/$ of an arithmetic


expression 3 written in 3ostfix notation.
,tep <: Add a right parentheses 2 at the end of 3
,tep :: ,can 3 from left to right and repeat step A and B for each element
of 3 until 2 is encountered
,tep A: If an operand is encountered# put the operand on the stac(
,tep B: If an operator is encountered # then:
1a2 5emo!e the two top elements of stac(# where A is top element
and 6 is next%top%element.
1b2 $!aluate 6 A
1c 2 3lace the result of 1b2 bac( on stac(
E$nd of if structureF
E$nd of step : loopF
,tep C: ,et =A)/$ e"ual to the top element of stac(
,tep J: $xit
*ransforming nfi( +(pression into Postfi( +(pression

The algorithm uses a stac( to temporarily hold operators and left


parentheses. The postfix expression 3 will be constructed from left to
right using operands from 9 and operators which are remo!ed from
,TACV. The algorithm begins by pushing a left parentheses onto
stack and adding a right parentheses at the end of Q

Algorithm: 3',T7Id 19# 32


,uppose 9 is an arithmetic expression written in infix
notation. This algorithm finds the e"ui!alent postfix
expression 3
,tep <: 3ush 1 on to the ,TACV and add 2 to the end of 9
,tep :: ,can 9 from left to right and repeat step A to J for each element
of 9 until the ,TACV is empty
,tep A: If an operand is encountered# add it to 3
,tep B: If left parentheses is encountered# add it to ,TACV
,tep C: If an operator is encountered# then:
1a2 5epeatedly pop from ,TACV and add to 3 each operator
which has same precedence or higher precedence than
1b2 Add to ,TACV
,tep J: If a right parentheses is encountered # then:
1a2 5epeatedly pop from ,TACV and add to 3 each operator until
a left parentheses is encountered
1b2 5emo!e the left parentheses
E$nd of ,tep : )oopF
,tep Z: $xit
$xample: Con!ert 9DAK16]C2 I &2 to its corresponding postfix form
,olution: put 2 at the end of 9 and put 1 on stac(

,tarting from left: 'perand A # put it on 3

'perator K mo!e to stac( as no operator there


1 mo!e on stac(
'perand 6# put it on 3

'perator ] # mo!e to stac( as no operator

'perand C # mo!e to 3
2 # pop from stac( and put on 3 until 1 is encountered.

3op 1 also

operator I# as precedence of I is higher than K on stac(# no pop

possible. 3ush I on stac(


'perand & # put it on 3

5ight parentheses 2# 3op all the elements and add the 3 until 1 is
encountered. Also remo!e 1 from stac(

3D A 6 C] & I K
=
%
%
>
=
%
=
%
?
*ransforming nfi( +(pression into Prefi( +(pression

Algorithm: E3olish +otationF 35$7Id 19# 32


,uppose 9 is an arithmetic expression written in infix
notation. This algorithm finds the e"ui!alent prefix
expression 3
,tep <: 5e!erse the input string
,tep :: $xamine the next element in the input
,tep A: If it is operand# add it to output string
,tep B: If it is closing parentheses# push it on stac(
,tep C: If it is operator# then:
1i2 if stac( is empty# push operator on stac(
1ii2 if top of stac( is closing parentheses# push operator on the
stac(
1iii2 If it has same or higher priority than top of stac(# push
operator on stac(
$lse pop the operator from the stac( and add it to output
string# repeat step C

,tep J: If it is an opening parentheses# pop operators from stac( and


add them to output string until a closing parentheses is encountered#
pop and discard the closing parentheses.

,tep Z: If there is more input go to step :

,tep [: If there is no more input# unstac( the remaining operators and


add them to output string

,tep \: 5e!erse the output string

Consider the following arithmetic expression 3 written in postfix


notation
3: <:# Z# A %# I# :# <# C# K# ]# K
1a2 Translate 3# by inspection and hand# into its e"ui!alent infix
expression
1b2 $!aluate the infix expression
,ol: 1a2 ,canning from left to right# translate each operator from postfix
to infix notation
3 D <:# EZ%AF# I# :# <# C# K# ]# K
D E<:IEZ%AFF#:# E<KCF#]#K
D <:I1Z%A2K:]1<KC2
1b2 <:I1Z%A2K:]1<KC2
D EAF#E:]JF#K
D AK<:
D <C
Practical applications of stack

,tac(s are used for implementing function calls in a program

/sed for implementing recursion.

/sed for con!ersion of infix expression to its postfix or prefix form

/sed for e!aluation of postfix expression.

/sed in sorting of arrays 1"uic(sort and mergesort techni"ue2


9/$/$

9ueue% A "ueue is a linear list of elements in which insertions can


ta(e place at one end called the rear of the "ueue# and deletion can
ta(e place only at other end# called the font of the "ueue. 9ueues are
also called the 7I7' lists 17irst In 7irst 'ut2 since first element in
"ueue is the first element out of the "ueue. An important example of a
"ueue in computer science occurs in time sharing systems in which
programs with same priority form a "ueue while waiting to be
executed.

9ueues may be represented in computer in !arious ways# usually


by means of one%way lists or linear arrays
/epresenting a Queue $sing an Array
A 9ueue is maintained by a linear array "ueue and two pointer !ariables: 75'+T#
containing the location of front element of the "ueue and 5$A5# containing the
location of rear element of the "ueue. The condition 75'+TD+/)) indicates that
"ueue is empty. Ghene!er an element is deleted from the "ueue# the !alue of
75'+T is increased by <. ,imilarly# whene!er an element is added to "ueue# the
!alue of 5$A5 is increased by <.
Queue as a circular :ueue
It can be seen that after + insertions in a 9ueue represented by an array of +
elements# the rear element of 9ueue will occupy last part of array. This occurs e!en
though the "ueue itself may not contain many elements. +ow# if we want to insert
an element IT$H into a "ueue# we ha!e to mo!e or rearrange the elements of entire
"ueue to the beginning of the "ueue. This procedure may be !ery expensi!e.
Another method to do so is to represent a "ueue as a circular "ueue i#e 9/$/$E<F
comes after 9/$/$E+F in array. Gith this assumption# we insert IT$H into "ueue
by assigning IT$H to 9/$/$E<F. Thus instead of increasing 5$A5 to +K<# we
reset 5$A5D< and then assign
9/$/$E5$A5FDIT$H
,imilarly# If 75'+TD+ and an element of 9/$/$ is deleted# we reset 75'+TD<
instead of increasing 75'+T to +K<
Algorithm for nserting in a Q$+$+

Algorithm: 9I+,$5T19/$/$# +# 75'+T# 5$A5#IT$H2


This algorithm inserts an element in a linear "ueue

,tep <:E9ueue already filledF


If 5$A5D+# then:
Grite: M'=$57)'G-
$xit

,tep :: If 75'+TD+/))# then: E9ueue initially emptyF


,et 75'+T:D< and 5$A5:D<
$lse:
,et 5$A5:D5$A5K<
E$nd of If structureF

,tep A: ,et 9/$/$E5$A5F:DIT$H

,tep B: 5eturn

Algorithm: 9&$)$T$19/$/$#+#75'+T#5$A5#IT$H2

This algorithm deletes an element from a "ueue

,tep <: If 75'+TD+/))# then:


Grite: M/+&$57)'G-
$xit

,tep :: ,et IT$H:D9/$/$E75'+TF

,tep A: If 75'+TD5$A5# then: E$mpty 9ueueF


,et 75'+T:D+/)) and 5$A5:D+/))
$lse:
,et 75'+T:D75'+TK<
E$nd of If structureF

,tep B: 5eturn
Algorithm: 9I+,$5T19/$/$# +# 75'+T# 5$A5#IT$H2
This algorithm inserts an element in a circular "ueue

,tep <:E9ueue already filledF


If 75'+TD< and 5$A5D+ or 75'+TD5$A5K<# then:
Grite: M'=$57)'G-
$xit

,tep :: If 75'+TD+/))# then: E9ueue initially emptyF


,et 75'+T:D< and 5$A5:D<
$lse If 5$A5D+# then:
,et 5$A5:D<
$lse:
,et 5$A5:D5$A5K<
E$nd of If structureF

,tep A: ,et 9/$/$E5$A5F:DIT$H

,tep B: 5eturn

Algorithm: 9&$)$T$19/$/$#+#75'+T#5$A5#IT$H2

This algorithm deletes an element from a circular "ueue

,tep <: If 75'+TD+/))# then:


Grite: M/+&$57)'G-
$xit

,tep :: ,et IT$H:D9/$/$E75'+TF

,tep A: If 75'+TD5$A5# then: E$mpty 9ueueF


,et 75'+T:D+/)) and 5$A5:D+/))
$lse If 75'+TD+# then:
,et 75'+T:D<
$lse:
,et 75'+T:D75'+TK<
E$nd of If structureF

,tep B: 5eturn

Consider the following "ueue of characters where 9/$/$ is a


circular array which is allocated six memory cells
75'+TD:# 5$A5DB 9/$/$: ^ A C & ^ ^
&escribe the "ueue as following operations ta(e place:
1a2 7 is added to "ueue
1b2 Two letters are deleted
1c2 V # ) and H are added
1d2 Two letters are deleted
1e2 5 is added to "ueue
1f2 Two letters are deleted
1g2 , is added to "ueue
1h2 Two letters are deleted
1i2 'ne letter is deleted
142 'ne letter is deleted

,olution:
1a2 75'+TD:# 5$A5DC 9/$/$: ^ A C & 7^
1b2 75'+TDB# 5$A5DC 9/$/$: ^ ^ ^ & 7 ^
1c2 5$A5D:# 75'+TDB 9/$/$: ) H ^ & 7 V
1d2 75'+TDJ# 5$A5D: 9/$/$: ) H ^ ^ ^ V
1e2 75'+TDJ# 5$A5DA 9/$/$: ) H 5^ ^ V
1f2 75'+TD:# 5$A5DA 9/$/$: ^H 5 ^ ^ ^
1g2 5$A5DB# 75'+TD: 9/$/$: ^ H 5 , ^ ^
1h2 75'+TDB# 5$A5DB 9/$/$: ^ ^ ^ , ^ ^
1i2 75'+TD5$A5D; E As 75'+TD5$A5# "ueue is emptyF
142 ,ince 75'+TD+/))# no deletion can ta(e place. /nderflow
occurred

D+Q$+3Double ended Queue5% A de"ue is a "ueue in which


elements can be added or remo!ed at either end but not in the middle.
A de"ue is usually maintained by a circular array &$9/$ with
pointers )$7T and 5I>8T# which point to two ends of de"ue. The
elements extend from )$7T end to 5I>8T end of de"ue. The term
circular comes from the fact that &$9/$E<F comes after &$9/$
E+F.The condition )$7TD+/)) will be used to indicate that a de"ue
is empty.

There are two !ariations of a de"ue

nput-restricted de:ue% It is a de"ue which allows insertions at only


one end of list but allows deletions at both ends of the list

!utput-restricted de:ue% It is a de"ue which allows deletions at only


one end of list but allows insertions at both ends of list

Consider the following de"ue of characters where &$9/$ is a circular array which
is allocated six memory cells.
)$7TD:# 5I>8TDB &$9/$: ^ A#C#&# ^ # ^

&escribe de"ue while the following operation ta(e place


1a2 7 is added to right of de"ue
)7$TD:# 5I>8TDC ^A C & 7 ^ ^
1b2 Two letters on right are deleted
)$7TD: 5I>8TDA ^A C ^ ^ ^ ^
1c2 V#) and H are added to the left of the de"ue
)$7TDC 5I>8TDA V A C ^ H )
1d2 'ne letter on left is deleted.
)$7TDJ 5I>8TDA V A C ^ ^ )
1e2 5 is added to the left of de"ue.
)$7TDC 5I>8TD A V A C ^ 5 )
1f2 , is added to right of de"ue
)$7TDC 5I>8TD B V A C , 5 )
1g2 T is added to the right of de"ue
,ince )$7TD 5I>8TK< # the array is full and hence T cannot be added to the
de"ue
Linked representation of the Queue

A lin(ed "ueue is a "ueue implemented as a lin(ed list with two


pointer !ariables 75'+T and 5$A5 pointing to the nodes in the
front and rear of the "ueue. The I+7' field of list hold the elements
of the "ueue and )I+V field holds pointer to neighboring element of
"ueue.

In case of insertion in lin(ed "ueue# a node borrowed from A=AI) list


and carrying the item to be inserted is added as the last node of lin(ed
list representing the "ueue. 5ear pointer is updated to point to last
node 4ust added to the list

In case of deletion# first node of list pointed to by 75'+T is deleted


and 75'+T pointer is updated to point to next node in the list.

/nli(e the array representation# lin(ed "ueue functions as a linear


"ueue and there is no need to !iew it as circular for efficient
management of space.
Algorithm:LN8QNS/*3I+7'#)I+V#75'+T#5$A5#A=AI)#IT$H2
This algorithm inserts an item in lin(ed list implementation of
the "ueue
,tep <: If A=AI)D+/))#then:
Grite: M'=$57)'G-
$xit
,tep :: ,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F
,tep A: ,et I+7'E+$GF:DIT$H and )I+VE+$GF:D+/))
,tep B: If 75'+TD+/))# then:
,et 75'+TD5$A5D+$G
$lse:
,et )I+VE5$A5F:D+$G and 5$A5:D+$G
,tep C: 5eturn
Algorithm: LN8QD+L3NF!7LN87F/!N*7A>AL7*+'5
This algorithm deletes an element from the front of the
"ueue

,tep <: If 75'+TD+/))#then:


Grite:-/+&$57)'G-
$xit

,tep :: ,et T$H3:D75'+T

,tep A: ,et IT$H:DI+7'E75'+TF

,tep B: ,et 75'+T:D)I+VE75'+TF

,tep C: ,et )I+VET$H3F:DA=AI) and A=AI):DT$H3

,tep J: 5eturn

Priority Queue- A priority "ueue is a collection of elements such that


each element has been assigned a priority and such that the order in
which elements are deleted and processed comes from following
rules:

An element of higher priority is processed before any element of


lower priority

Two elements of same priority are processed according to the order in


which they were added to "ueue

An example of a priority "ueue is a time sharing system. 3rograms of


higher priority are processed first and programs with same priority
form a standard "ueue
!ne-&ay list representation of a priority :ueue

'ne way to maintain a priority "ueue in memory is by means of a


one%way list

$ach node in list will contain three items of information: an


information field I+7'# a priority number 35+ and a lin( field )I+V

A node d precedes a node 0 in list



.
If d has higher priority than 0
.
'r when both ha!e same priority but d was added to list before 0
Algorithm:L8QNS3I+7'#)I+V#75'+T#35+#A=AI)#IT$H# 32
This algorithm inserts an item in lin(ed list implementation of priority "ueue
,tep <: If A=AI)D+/))#then:
Grite: M'=$57)'G-
$xit
,tep :: ,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F
,tep A: E$nter the data and priority of new nodeF ,et I+7'E+$GF:DIT$H and 35+E+$GF:D3
,tep B: ,et 3T5:D75'+T
,tep C: If 35+E3T5FN35+E+$GF# then
)I+VE+$GF:D75'+T
75'+T:D+$G
5eturn
E$nd of If ,tructureF
,tep C: 5epeat while 3T5S+/)) and 35+E3T5FUD35+E+$GF
,et ,A=$:D3T5
,et 3T5:D)I+VE3T5F
E$nd of If ,tructureF
,tep J: If 35+E3T5FN35+E+$GF
,et )I+VE,A=$F:D+$G
,et )I+VE+$GF:D3T5
$lse:
,et )I+VE,A=$F:D+$G
,et )I+VE+$GFD+/))
E$nd of If ,tructureF

,tep Z: 5eturn

Another way to maintain a priority "ueue in memory is to use a


separate "ueue for each le!el of priority . $ach such "ueue will appear
in its own circular array and must ha!e its own pair of pointers#
75'+T and 5$A5.

If each "ueue is allocated the same amount of space# a two


dimensional array 9/$/$ can be used instead of the linear arrays for
representing a priority "ueue. If V represents the row V of the "ueue#
75'+TEVF and 5$A5EVF are the front and rear indexes of the V
th

row.
< : A B C J
< AAA
: 666 CCC ddd
A
B 777 &&& $$$
C >>>
@
r
i
o
r
i
t
*
Algorithm: 9I+,$5T1 9/$/$#+# 75'+T# 5$A5#IT$H#V2
This algorithm inserts an element in a priority "ueue in a row with priority
V. + is the size of the V
th
row.

,tep <:E9ueue already filledF


If 75'+TEVFD< and 5$A5EVFD+ or 75'+TEVFD5$A5EVFK<# then:
Grite: M'=$57)'G-
$xit

,tep :: If 75'+TEVFD+/))# then: E9ueue initially emptyF


,et 75'+TEVF:D< and 5$A5EVF:D<
$lse If 5$A5EVFD+# then:
,et 5$A5EVF:D<
$lse:
,et 5$A5EVF:D5$A5EVFK<
E$nd of If structureF

,tep A: ,et 9/$/$EVFE5$A5EVFF:DIT$H

,tep B: 5eturn

Algorithm: 9&$)$T$19/$/$#+#75'+T#5$A5#IT$H# ,TA5T# HAd32

This algorithm deletes an element from a priority "ueue. HAd3 is the

maximum priority in the array

,tep <: ,et VD< E3riority numberF

,tep :: 5epeat while VUDHAd3 and 75'+TEVFD+/))


,et VDVK<
E$nd of )oopF

,tep A: If VNHAd3 # then:


Grite:-/+&$57)'G-
$xit
E$nd of If structureF

,tep B: ,et IT$H:D9/$/$EVFE75'+TEVFF

,tep C: If 75'+TEVFD5$A5EVF# then: E$mpty 9ueueF


,et 75'+TEVF:D+/)) and 5$A5EVF:D+/))
$lse If 75'+TEVFD+# then:
,et 75'+TEVF:D<
$lse:
,et 75'+TEVF:D75'+TEVFK<
E$nd of If structureF

,tep C: 5eturn
*/++

A tree is a non%linear data structure mainly used to represent data


containing hierarchical relationship between elements. In hierarchical
data we ha!e ancestor%descendent# superior%subordinate# whole%part#
or similar relationship among data elements.

A 1general2 tree T is defined as a finite nonempty set of elements such


that

There is a special node at the highest le!el of hierarchy called the


root#

and the remaining elements # if any# are partitioned into dis4oint sets
T
<
#T
:
#T
A
%%%T
n
where each of these sets is a tree# called the sub tree of
T.

In other words# one may define a tree as a collection of nodes and


each node is connected to another node through a branch. The nodes
are connected in such a way that there are no loops in the tree and
there is a distinguished node called the root of the tree.

*ree *erminology
Parent node- If + is a node in T with left successor ,
<
and right successor ,
:
# then
+ is called father or parent of ,
<
and ,
:
. ,imilarly# ,
<
is called left child of + and ,
:

is called the right child of +. The child node is also called the descendant of a node
+

Siblings- The child nodes with same parent are called siblings

Le#el of element- $ach node in tree is assigned a le!el number. 6y definition# root
of the tree is at le!el ;*its children# if any# are at le!el <* their children# if any# are at
le!el :* and so on. Thus a node is assigned a le!el number one more than the le!el
number of its parent

Depth%9eight of *ree- The height or depth of tree is maximum number of


nodes in a branch . It is one more than the ma(imum le#el number
of the tree.

Degree of an element- The degree of a node in a tree is number of children it has.


The degree of leaf node is zero.

Degree of *ree- The degree of a tree is the maximum degree of its nodes.

+dge- )ine drawn from a node + of T to a successor is called an edge.

Path- A se"uence of edges is called an path

Leaf- A terminal node of a tree is called leaf node

,ranch- 3ath ending in a leaf is called branch of the tree

The most common form of tree maintained in computer is binary tree.

,inary *ree- A binary tree T is defined as a finite set of elements#


called nodes# such that either:
.
T is empty 1called null tree or empty tree2 or#
.
T contains a distinguished node# 5# called root of T and remaining
nodes of T form an ordered pair of dis4oint binary trees T< and T:

Two trees T< and T: are called respecti!ely left and right subtree of 5
1root node of T2. If T< is nonempty# then its root is called left
successor of 5. ,imilarly# If T: is nonempty# then its root is called
right successor of 5
A
6 C
& $ > 8
7 W V
)

The nodes &#7#>#)#V are the terminal or leaf nodes


Root No9e
%4ight !uccessor of 5& %+eft !uccessor of 5&

6ianry trees are used to represent algebraic expressions in!ol!ing


only binary operations# such as

$D 1a%b2I11c]d2Ke2

$ach !ariable or constant in $ appears as an internal node in T whose


left and right subtree correspond to operands of the expression
I

% K
a b ] e

c d

6efore constructing a tree for an algebraic expression# we ha!e to see


the precedence of the operators in!ol!ed in the expression.

Difference bet&een binary tree and a general tree
A binary tree can be empty whereas a tree cannot be empty
$ach element in binary tree has at most two sub trees whereas each
element in a tree can ha!e any number of sub trees
The sub trees of each element in a binary tree are ordered. That is we
can distinguish between left and right sub trees. The sub trees in a tree
are unordered.
Properties of ,inary *rees
$ach node of a binary tree T can ha!e at most two children. Thus at le!el r of t#
there can be atmost :
r
nodes.
The number of nodes in a tree for gi!en number of le!els in a tree is
:
n
%<
&epth of a tree T with n nodes is gi!en by
&
n
D log
:
n K <
&
n
h log
:
n
"omplete ,inary tree- A binary tree T is said to be complete if all its le!els# except
possibly the last# ha!e maximum number of possible nodes# and if all the nodes at
last le!el appear as far left as possible. Thus there is a uni"ue complete tree T with
exactly n nodes.
+(tended ,inary *rees: B-*rees- A binary tree is said to be a :%tree or an extended
binary tree if each node + has either ; or : children. In such a case# nodes with :
children are called internal nodes# and nodes with ; child are called external nodes.
The external and internal nodes are distinguished diagrammatically by using circles
for internal nodes and s"uares for external nodes

/epresenting ,inary *rees in memory
6inary trees can be represented
using lin(ed list
using a single array called the se"uential representation of tree
Se:uential representation of ,inary *rees- This representation uses
only a single linear array Tree as follows:
The root 5 of T is stored in T5$$E<F
If a node + occupies T5$$EVF# then its left child is stored in
T5$$E:]VF and its right child is stored in T5$$E:]VK<F
BC
:: ZZ
<< A; \;
<C :C [[
BC
::
ZZ
<<
A;
;
\;
;
<C
:C
;
;
;
A:++
A:++
A:++
A:++
A:++
[[
It can be seen that a se"uential representation of a binary tree re"uires
numbering of nodes* starting with nodes on le!el <# then on le!el :
and so on. The nodes are numbered from left to right .
It is an ideal case for representation of a complete binary tree and in
this case no space is wasted. 8owe!er for other binary trees# most of
the space remains unutilized. As can be seen in the figure# we re"uire
<B locations in array e!en though the tree has only \ nodes. If null
entries for successors of the terminal nodes are included# we would
actually re"uire :\ locations instead of <B.Thus se"uential
representation is usually inefficient unless binary tree is complete or
nearly complete
Linked representation of ,inary *ree
In lin(ed representation# Tree is maintained in memory by means of
three parallel arrays# I+7'# )$7T and 5I>8T and a pointer !ariable
5''T. $ach node + of T will correspond to a location V such that
NF!<8= contains data at node +. L+F*<8= contains the location of
left child of node + and /09*<8= contains the location of right
child of node +. /!!* will contain location of root 5 of Tree. If any
subtree is empty# corresponding pointer will contain null !alue. If the
tree T itself is empty# then 5''T will contain null !alue
5
B 7
2
1 C D
E
# F
4$$T
*ra#ersing ,inary *rees
There are three standard ways of tra!ersing a binary tree T with root
5. These are preorder# inorder and postorder tra!ersals

Preorder
35'C$,, the root 5
Tra!erse the left sub tree of 5 in preorder
Tra!erse the right sub tree of 5 in preorder

norder
Tra!erse the left sub tree of 5 in inorder
3rocess the root 5
Tra!erse the right sub tree of 5 in inorder

Postorder
Tra!erse the left sub tree of 5 in postorder
Tra!erse the right sub tree of 5 in postorder
3rocess the root 5

The difference between the algorithms is the time at which the root 5
is processed. In pre algorithm# root 5 is processed before sub trees are
tra!ersed* in the in algorithm# root 5 is processed between tra!ersals
of sub trees and in post algorithm # the root is processed after the sub
trees are tra!ersed.
A
6 C
& $ 7

3reorder Tra!ersal: A 6 & $ C 7

Inorder Tra!ersal: & 6 $ A C 7

3ostorder Tra!ersal : & $ 6 7 C A

All the tra!ersal algorithms assume a binary tree T maintained in


memory by lin(ed representation
T5$$1I+7'#)$7T#5I>8T#5''T2

All algorithms use a !ariable 3T51pointer2 which will contain the


location of the node + currently being scanned. )$7TE+F denotes the
left child of node + and 5I>8TE+F denotes the right child of +. All
algorithms use an array ,TACV which will hold the addresses of
nodes for further processing.

Algorithm: P/+!/D3NF!7 L+F*7 /09*7 /!!*5


This algorithm tra!erses the tree in preorder

,tep <: ,et T'3:D<# ,TACVE<F:D+/)) and 3T5:D 5''T

,tep :: 5epeat ,tep A to C while 3T5S+/))

,tep A: Apply 35'C$,, to I+7'E3T5F

,tep B: E5ight Child QF


If 5I>8TE3T5F S +/))# then:
,et T'3:DT'3 K <
,et ,TACVET'3F:D 5I>8TE3T5F
E$nd of If structureF

,tep C: E)eft Child QF


If )$7TE3T5F S +/))# then:
,et 3T5:D)$7TE3T5F
$lse:
,et 3T5:D,TACVET'3F
,et T'3:DT'3%<
E$nd of If structureF
E$nd of ,tep : )oopF

,tep J: 5eturn

Algorithm: N!/D 3NF!7 L+F*7/09*7 /!!*5

,tep <: ,et T'3:D<# ,TACVE<F:D+/)) and 3T5:D5''T

,tep :: 5epeat while 3T5 S +/)):


1A2 ,et T'3:DT'3 K < and ,TACVET'3F:D 3T5
162 ,et 3T5:D)$7TE3T5F
E$nd of )oopF

,tep A: ,et 3T5:D,TACVET'3F and T'3:DT'3 %<

,tep B: 5epeat ,tep C to Z while 3T5 S +/))

,tep C: Apply 35'C$,, to I+7'E3T5F

,tep J: If 5I>8TE3T5F S +/))# then:


1A2 ,et 3T5 :D 5I>8TE3T5F
162 >' T' step :
E$nd of If structureF

,tep Z: ,et 3T5:D,TACVET'3F and T'3:DT'3 %<


E$nd of ,tep B )oopF

,tep [: 5eturn

Algorithm : P!S*!/D3 NF!7 L+F*7 /09*7 /!!*5

,tep <: ,et T'3:D<# ,TACVE<F:D+/)) and 3T5:D5''T

,tep :: 5epeat ,tep A to C while 3T5S +/))

,tep A: ,et T'3:DT'3 K< and ,TACVET'3F:D3T5

,tep B: If 5I>8TE3T5FS +/))# then:


,et T'3:DT'3 K< and ,TACVET'3F:D % 5I>8TE3T5F
E$nd of If structureF

,tep C: ,et 3T5:D)$7TE3T5F


E$nd of ,tep : loopF

,tep J: ,et 3T5:D,TACVET'3F and T'3:DT'3 %<

,tep Z: 5epeat while 3T5N;:


1A2 Apply 35'C$,, to I+7'E3T5F
162 ,et 3T5:D,TACVET'3F and T'3:DT'3 %<
E$nd of )oopF

,tep [: If 3T5U;# then:


1a2 ,et 3T5:D%3T5
1b2 >o to ,tep :
E$nd of If structureF

,tep \: $xit
3roblem: Create a tree from the gi!en tra!ersals
preorder: 7 A $ V C & 8 > 6
inorder: $ A C V 7 8 & 6 >
,olution: The tree is drawn from the root as follows:
1a2 The root of tree is obtained by choosing the first node of preorder.
Thus 7 is the root of the proposed tree
1b2 The left child of the tree is obtained as follows:
1a2 /se the inorder tra!ersal to find the nodes to the left and right of
the root node selected from preorder. All nodes to the left of root
node1in this case 72 in inorder form the left subtree of the root1in
this case $ A C V 2
1b2 All nodes to the right of root node 1in this case 7 2 in inorder
form the right subtree of the root 18 & 6 >2
1c2 7ollow the abo!e procedure again to find the subse"uent roots
and their subtrees on left and right.

7 is the root +odes on left subtree1 left of 72:$ A C V 1from inorder2


+odes on right subtree1right of 72:8 & 6 >1from inorder2

The root of left subtree:

7rom preorder: A $ V C # Thus the root of left subtree is A

D 8 > 6 # Thus the root of right subtree is &

Creating left subtree first:


7rom inorder: elements of left subtree of A are: + 1root of left2
elements of right subtree of A are: " V 1root of right2
Thus tree till now is:
7
A &

$ V
C
As V is to the left of C in preorder

Creating the right subtree of 7

The root node is &

7rom inorder# the nodes on the left of & are: 9 1left root of &2
the nodes on the right of & are: 6 0 3right root of D5
Thus the tree is:
7
A &
$ V 8 >
C 6

7
A &
$ V 8 >
C 6

*hreads: norder *hreading

Considering lin(ed list representation of a binary tree# it can be seen


that half of the entries in pointer fields )$7T and 5I>8T will contain
null entries. This space may be more efficiently used by replacing the
null entries by special pointers called Threads which point to nodes
higher in tree. ,uch trees are called *hreaded trees.

The threads in a threaded tree are usually indicated by dotted lines . In


computer memory# threads may be represented by negati!e integers
when ordinary pointers are denoted by positi!e integers.

There are many ways to thread a binary tree T but each threading will
correspond to a particular tra!ersal of T. Trees can be threaded using
one-&ay threading or t&o-&ay threading. /nless otherwise stated#
threading will correspond to inorder tra#ersal of *.

Accordingly# in one-&ay threading# a thread will appear in right null


field of a node and will point to the next node in inorder tra!ersal of T

In t&o-&ay threading of T# a thread will also appear in the )$7T


field of a node and will point to the preceding node in inorder
tra!ersal of T

A
6 C
& $ > 8
7 W V
)
'ne%way inorder Threading
Inorder tra!ersal: & 6 7 $ A > C ) W 8 V

A
6 C
& $ > 8
7 W V
)
Two%way inorder Threading

6inary ,earch Tree% If T is a binary tree# then T is called a binary search tree or
binary sorted tree if each node + of T has the following property:
.
The =alue of + is greater than e!ery !alue in left sub tree of +
.
The !alue at + is less than or e"ual to e!ery !alue in right sub tree of +

The inorder tra!ersal of 6,T gi!es sorted numbers


7or example: The following numbers create a 6,T as:

A C \ < : J [ <;
A
< C

: \
J <;

[

6inary search tree is one of the most important data structures in


computer science. This structure enables one to search for and find an
element with an a!erage running time
f1n2D'1log
:
n 2

It also enables one to easily insert and delete elements. This structure
contrasts with following structures:

,orted linear array% here one can find the element with a
running time of '1log
:
n 2 but it is expensi!e to insert and
delete

)in(ed list% 8ere one can easily insert and delete but searching
is expensi!e with running time of '1n2
Searching and nserting in a ,S*

Algorithm: This algorithm searches for IT$H in a tree and inserts it if


not present in tree

,tep <: Compare IT$H with root node + of Tree


1i2 If IT$H U +# proceed to left child of +
1ii2 If IT$H ND +# proceed to right child of +

,tep :: 5epeat step < until one of the following occurs:


1i2 If IT$H D +# then:
Grite: M,earch successful-
1ii2 $mpty sub tree found indicating search unsuccessful.
Insert item in place of empty sub tree
Algorithm: NS,*3NF!7 L+F*7 /09*7 A>AL7 *+'7 L!"5
This algorithm finds the location )'C of an IT$H in T or adds IT$H as a new
node in T at location )'C
,tep <: Call 7I+&1I+7'# )$7T# 5I>8T# 5''T# IT$H# )'C# 3A52
,tep :: If )'C S +/))# then
5eturn
,tep A: ECopy item into new node in A=AI) listF
1a2 If A=AI)D+/))# then:
Grite: M'=$57)'G-
5eturn
1b2 ,et +$G:DA=AI)# A=AI):D)I+VEA=AI)F and
I+7'E+$GF:DIT$H
1c2 ,et )$7TE+$GF:D+/)) and 5I>8TE+$GF:D+/))
,tep B:EAdd IT$H to treeF
If 3A5D+/))# then:
,et 5''T:D+$G
$lse If IT$HUI+7'E3A5F# then:
,et )$7TE3A5F:D+$G
$lse:
,et 5I>8TE3A5F:D+$G
E$nd of If structureF
,tep C: 5eturn

Algorithm: FND3NF!7L+F*7/09*7/!!*7*+'7L!"7PA/5
This algorithm finds the location )'C of IT$H in T and also the location 3A5 of the parent of
IT$H. There are three special cases
1a2 )'CD+/)) and 3A5D+/)) will indicate tree is empty
1b2 )'CS +/)) and 3A5D+/)) will indicate that IT$H is the root of T
1 c2 )'CD+/)) and 3A5 S +/)) will indicate that IT$H is not in T and can be added to T as
a child of node + with location 3A5
,tep <: If 5''TD +/)) # then:
,et )'C:D+/)) and 3A5:D+/))
5eturn
,tep :: If IT$HDI+7'E5''TF# then:
,et )'C:D5''T and 3A5:D+/))
Grite: -Item is the root of the tree-
5eturn
,tepA: If IT$H U I+7'E5''TF# then:
,et 3T5:D)$7TE5''TF and ,A=$:D5''T
$lse:
,et 3T5:D5I>8TE5''TF and ,A=$:D 5''T
E$nd of If structureF
,tep B: 5epeat while 3T5 S +/)):
If IT$HDI+7'E3T5F #then:
,et )'C:D3T5 and 3A5:D,A=$
Grite: M the location of the node in tree is-# )'C
5eturn
If IT$HU I+7'E3T5F # then:
,et ,A=$:D3T5 and 3T5:D)$7TE3T5F
$lse:
,et ,A=$:D3T5 and 3T5:D5I>8TE3T5F
E$nd of If structureF
E$nd of ,tep B )oopF
,tep C: E,earch unsuccessfulF ,et )'C:D+/)) and 3A5:D,A=$
,tep J: 5eturn

Deletion in a ,inary Search *ree% &eletion in a 6,T uses a


procedure 7I+& to find the location of node + which contains IT$H
and also the location of parent node 31+2. The way + is deleted from
the tree depends primarily on the number of children of node +. There
are three cases:

"ase A: + has no children. Then + is deleted from T by simply


replacing the location 31+2 by null pointer

"ase B: + has exactly one child. Then + is deleted from T by simply


replacing the location of + by location of the only child of +

"ase D: + has two children. )et ,1+2 denote the inorder successor of
+. Then + is deleted from T by first deleting ,1+2 from T1by
using Case < or Case :2 and then replacing node + in T by
node ,1+2

Case <: Ghen node to be deleted does not ha!e two children
Algorithm: &$)A1 I+7'# )$7T#5I>8T#5''T#)'C#3A52
This procedure deletes node + at location )'C where +
does not ha!e two children. 3A5 gi!es the location of
parent node of + or else 3A5D+/)) indicating + is the
root node. 3ointer C8I)& gi!es the location of only child
of +

,tep <: If )$7TE)'CFD+/)) and 5I>8TE)'CFD+/))# then:


,et C8I)&D+/))
$lse If )$7TE)'CFS+/))# then:
,et C8I)&:D)$7TE)'CF
$lse
,et C8I)&:D5I>8TE)'CF

,tep :: If 3A5 S +/))# then:


If )'CD)$7TE3A5F # then:
,et )$7TE3A5F:DC8I)&
$lse:
,et 5I>8TE3A5F:DC8I)&
$lse:
,et 5''T:DC8I)&

,tep A: 5eturn

"ase B: ?hen node to be deleted has t&o children

Algorithm: D+L,3 NF!7 L+F*7 /09*7 /!!*7 L!"7 PA/7 S$"7 PA/S$"5
This procedure deletes node + at location )'C where + ha!e two children. 3A5
gi!es the location of parent node of + or else 3A5D+/)) indicating + is the
root node. 3ointer ,/C gi!es the location of in order successor of + and 3A5,/C
gi!es the location of parent of in order successor
,tep <: 1a2 Set P*/:@/09*<L!"= and SA>+:@L!"
3b5 /epeat &hile L+F*<P*/=EN$LL
Set SA>+:@P*/ and P*/:@L+F*<P*/=
<+nd of Loop=
3c 5 Set S$":@P*/ and PA/S$":@SA>+
Step B: "ALL D+LA3NF!7L+F*7/09*7 /!!*7S$"7PA/S$"5
Step D: 3a5 f PA/ E N$LL7 then:
f L!" @ L+F* <PA/=7 then:
Set L+F*<PA/=:@S$"
+lse:
Set /09*<PA/=:@S$"
<+nd of f structure=
+lse:
Set /!!*:@S$"
<+nd of f structure=

1b2 ,et )$7TE,/CF:D)$7TE)'CF and
,et 5I>8TE,/CF:D5I>8TE)'CF

,tep B: 5eturn
8eaps

A heap is a binary tree T that stores a (ey%element pairs at its


internal nodes

It satisfies two properties:

'in9eap: key3parent5 key3child5

<!/ 'a(9eap: key3parent5 key3child5=

all le!els are full# except


the last one# which is
left%filled
B
J
:; Z
[ <<
C
\
<: <B
<C
:C <J
9eap
,uppose 8 is a complete binary tree with n elements. Then 8 is called
a heap or a maxheap if each node + of 8 has the property that !alue
of + is greater than or e"ual to !alue at each of the children of +.
\Z
[[ \C
JJ CC \C B[
JJ AC B[ CC J: ZZ :C A[
<[ B; A; :J :B
Analogously# a minheap is a heap such that !alue at + is less than or
e"ual to the !alue of each of its children. 8eap is more efficiently
implemented through array rather than lin(ed list. In a heap# the
location of parent of a node 3T5 is gi!en by 3T5I:
nserting an element in a 9eap
,uppose 8 is a heap with + elements# and suppose an IT$H of
information is gi!en. Ge insert IT$H into the heap 8 as follows:
7irst ad4oin the IT$H at the end of 8 so that 8 is still a complete tree
but not necessarily a heap
Then let the IT$H rise to its appropriate place in 8 so that 8 is finally
a heap
Algorithm: I+,8$A31 T5$$# +# IT$H2
A heap 8 with + elements is stored in the array T5$$ and an IT$H of
information is gi!en. This procedure inserts the IT$H as the new element
of 8. 3T5 gi!es the location of IT$H as it rises in the tree and 3A5
denotes the parent of IT$H
,tep <: ,et +:D + K< and 3T5:D+
,tep :: 5epeat ,tep A to J while 3T5 N <
,et 3A5:D3T5I:
If IT$H P T5$$E3A5F# then:
,et T5$$E3T5F:DIT$H
5eturn
,et T5$$E3T5F:DT5$$E3A5F
E$nd of If structureF
,et 3T5:D3A5
E$nd of )oopF
,tep A: ,et T5$$E<F:DIT$H
,tep B: 5eturn
Deleting the root node in a heap
,uppose 8 is a heap with + elements and suppose we want to delete
the root 5 of 8. This is accomplished as follows:
Assign the root 5 to some !ariable IT$H
5eplace the deleted node 5 by last node ) of 8 so that 8 is still a
complete tree but not necessarily a heap
)et ) sin( to its appropriate place in 8 so that 8 is finally a heap
Algorithm: &$)8$A31 T5$$# + # IT$H 2
A heap 8 with + elements is stored in the array T5$$.
This algorithm assigns the root T5$$E<F of 8 to the
!ariable IT$H and then reheaps the remaining elements.
The !ariable )A,T stores the !alue of the original last
node of 8. The pointers 3T5# )$7T and 5I>8T gi!e the
location of )A,T and its left and right children as )A,T
sin(s into the tree.
,tep <: ,et IT$H:DT5$$E<F
,tep :: ,et )A,T:DT5$$E+F and +:D+%<
,tep A: ,et 3T5:D<# )$7T:D: and 5I>8T:DA
,tep B: 5epeat step C to Z while 5I>8T P +:
,tep C: If )A,T R T5$$E)$7TF and )A,T R T5$$ E5I>8TF # then:
,et T5$$E3T5F:D)A,T
5eturn
,tep J: If T5$$E5I>8TFP T5$$E)$7TF# then:
,et T5$$E3T5F:DT5$$E)$7TF
,et 3T5:D)$7T
$lse:
,et T5$$E3T5F:DT5$$E5I>8TF and 3T5:D5I>8T
E$nd of If structureF
,et )$7T:D :] 3T5 and 5I>8T:D)$7T K <
E$nd of )oopF
,tep Z: If )$7TD+ and If )A,T U T5$$E)$7TF# then:
,et T5$$E3T5F:DT5$$E)$7TF and ,et 3T5:D)$7T
,tep [: ,et T5$$E3T5F:D)A,T
5eturn

\;
[; [C
J; C; ZC Z;
Application of 9eap
8eap,ort% 'ne of the important applications of heap is sorting of an
array using heapsort method. ,uppose an array A with + elements is
to be sorted. The heapsort algorithm sorts the array in two phases:
3hase A: 6uild a heap 8 out of the elements of A
3hase 6: 5epeatedly delete the root element of 8
,ince the root element of heap contains the largest element of the
heap# phase 6 deletes the elements in decreasing order. ,imilarly#
using heapsort in minheap sorts the elements in increasing order as
then the root represents the smallest element of the heap.
Algorithm: 8$A3,'5T1A#+2
An array A with + elements is gi!en. This algorithm sorts
the elements of the array
,tep <: E6uild a heap 8F
5epeat for WD< to +%<:
Call I+,8$A31A# W# AEWK<F2
E$nd of )oopF
,tep :: E,ort A repeatedly deleting the root of 8F
5epeat while + N <:
1a2 Call &$)8$A31 A# +# IT$H2
1b2 ,et AE+ K <F :D IT$H E,tore the elements deleted from
the heapF
E$nd of loopF
,tep A: $xit
3roblem: Create a 8eap out of the following data:
4an feb mar apr may 4un 4ul aug sept oct no! dec
,olution:
&ec

'ct +o!
Wuly ,ept Wune Hay

Wan April Har Aug 7eb
A>L */++
The efficiency of many important operations on trees is related to the
height of the tree .for example searching# insertion and deletion in a
6,T are all '1height2. In general# the relation between the height of
the tree and the number of nodes of the tree is ' 1log
:
n2 except in the
case of right s(ewed or left s(ewed 6,T in which height is '1n2. The
right s(ewed or left s(ewed 6,T is one in which the elements in the
tree are either on the left or right side of the root node.
A A
6 6
C C
& &
$ $
4ight-s-e(ed +eft-s-e(ed

7or efficiency sa(e# we would li(e to guarantee that h remains


'1log
:
n2. 'ne way to do this is to force our trees to be height%
balanced.

Hethod to chec( whether a tree is height balanced or not is as


follows:
.
,tart at the lea!es and wor( towards the root of the tree.
.
Chec( the height of the subtrees1left and right2 of the node.
.
A tree is said to be height balanced if the difference of heights of
its left and right subtrees of each node is e"ual to ;# < or %<

$xample:

Chec( whether the shown tree is balanced or not


A
6 C

&
,ol: ,tarting from the leaf nodes & and C# the height of left and right
subtrees of C and & are each ;. Thus their difference is also ;

Chec( the height of subtrees of 6


8eight of left subtree of 6 is < and height of right subtree of 6 is ;.
Thus the difference of two is < Thus 6 is not perfectly balanced but
the tree is still considered to be height balanced.

Chec( the height of subtrees of A


8eight of left subtree of A is : while the height of its right subtree is
<. The difference of two heights still lies within <.

Thus for all nodes the tree is a balanced binary tree.


Chec( whether the shown tree is balanced or not


A

6 7

C
&
$
Ans +o as node 6 is not balanced as difference of heights of left and
right subtrees is A%; i.e more than <.
9eight-balanced ,inary tree 3A>L *ree5
The disad!antage of a s(ewed binary search tree is that the worst case
time complexity of a search is '1n2. In order to o!ercome this
disad!antage# it is necessray to maintain the binary search tree to be
of balanced height. Two 5ussian mathematicians # >.H. Adel and
$.H. )andis ga!e a techni"ue to balance the height of a binary tree
and the resulting tree is called A=) tree.
Definition: An empty binary tree is an A=) tree. A non empty binary
tree T is an A=) tree iff gi!en T
)
and T
5
to be the left and right
subtrees of T and h1T
)
2 and h1T
5
2 be the heights of subtrees T
)
and T
5

respecti!ely# *
L
and *
/
are A>L trees and Fh3*
L
5-h3*
/
5F G A;
Oh1T
)
2%h1T
5
2O is also called the balance factor 1672 and for an A=) tree
the balance factor of a node can be either %<# ; or <
An A>L search tree is a binary search tree &hich is an A>L tree;

A node in a binary tree that does not contain the 67 of ;# < or %<# it is
said to be unbalanced. If one inserts a new node into a balanced
binary tree at the leaf# then the possible changes in the status of the
node are as follows:

The node was either left or right hea!y and has now become balanced.
A node is said to be left hea!y if number of nodes in its left subtree
are one more than the number of nodes in its right subtree.. In other
words# the difference in heights is <. ,imilar is the case with right
hea!y node where number of nodes in right subtree are one more than
the number of nodes in left subtree

The node was balanced and has now become left or right hea!y

The node was hea!y and the new node has been inserted in the hea!y
subtree# thus creating an unbalanced subtree. ,uch a node is called a
critical node;
/otations- Inserting an element in an A=) search tree in its first phase
is similar to that of the one used in a binary search tree. 8owe!er# if
after insertion of the element# the balance factor of any node in a
binary search tree is affected so as to render the binary search tree
unbalanced# we resort to techni"ues called 5otations to restore the
balance of the search tree.

To perform rotations# it is necessary to identify the specific node A


whose 67 1balance factor2 is neither ;#< or %< and which is nearest
ancestor to the inserted node on the path from inserted node to the
root.

The rebalancing rotations are classified as ))# )5# 55 and 5) based


on the position of the inserted node with reference to A
LL rotation: Inserted node in the left subtree of the left subtree of A
// rotation: Inserted node in the right subtree of the right subtree of A
L/ rotation: Inserted node in the right subtree of the left subtree of A
/L rotation: Inserted node in the left subtree of the right subtree of A

LL /otation- This rotation is done when the element is inserted in the left subtree
of the left subtree of A. To rebalance the tree# it is rotated so as to allow 6 to be the root
with 6
)
and A to be its left subtree and right child and 6
5
and A
5
to be the left and right
subtrees of A. The rotation results in a balanced tree.

// /otation%This rotation is applied if the new element is inserted right


subtree of right subtree of A. The rebalancing rotation pushes 6 upto the root with A as
its left child and 6
5
as its right subtree and A
)
and 6
)
as the left and right subtrees of A
L/ and /L rotations- The balancing methodology of )5 and 5) rotations are similar in
nature but are mirror images of one another. Amongst the rotations# LL and // rotations are
called as single rotations and L/ and /L are (nown as double rotations since )5 is
accomplished by 55 followed by )) rotation and 5) can be accomplished by )) followed by
55 rotation. L/ rotation is applied &hen the ne& element is inserted in right subtree of the
left subtree of A; /L rotation is applied &hen the ne& element is inserted in the left subtree
of right subtree of A
)5 5otation% this rotation is a combination of 55 rotation followed by
)) rotation.
A A C
6 A5 C A5 6 A
6) C 6 C5 6) C) C5 A5
C) C5 6) C) x

x x
RR %%
5) 5otation%This rotation occurs when the new node is inserted in left
subtree of right subtree of A. It-s a combination of )) followed by 55
A C

T
<
6 A 6
C T
B
T
<
T
:
T
A
T
B

T
:
T
A
+$G
+$G
R%

5) 5otation% This rotation occurs when the new node is inserted in right subtree of
left subtree of A.
A A

T
<
6 T
<
C
C T
B
T
:
6
T
:
T
A
+$G T
A
T
B

+$G //
C
A 6
T< T: TA TB
+$G


%%
3roblem: Construct an A=) search tree by inserting the following
elements in the order of their occurrence
JB# <# <B# :J# <A# <<;# \[# [C
,ol:
Deletion in an A>L search *ree
The deletion of element in A=) search tree leads to imbalance in the
tree which is corrected using different rotations. The rotations are
classified according to the place of the deleted node in the tree.
'n deletion of a node d from A=) tree# let A be the closest ancestor
node on the path from d to the root node with balance factor of K: or
%: .To restore the balance# the deletion is classified as ) or 5
depending on whether the deletion occurred on the left or right sub
tree of A.
&epending on !alue of 67162 where 6 is the root of left or right sub
tree of A# the 5 or ) rotation is further classified as 5;# 5< and
5%< or );# )< and )%<. The ) rotations are the mirror images of their
corresponding 5 rotations.
R8 Rotation2 This rotation is applie9 when the * of * is 8 after 9eletion of the
no9e
R- Rotation2 This rotation is applie9 when the * of * is -
R2- Rotation2 This rotation is applie9 when the * of * is 2-
) rotations are the mirror images of 5 rotations. Thus ); will be
applied when the node is deleted from the left subtree of A and the 67
of 6 in the right subtree is ;
,imilarly# )<and )%< will be applied on deleting a node from left
subtree of A and if the 67 of root node of right subtree of A is either <
or %< respecti!ely.
0/AP9
0raph% A graph > consists of :
. A set = of elements called the nodes 1or points or !ertices2
. A set $ of edges such that each edge e in $ is identified with a
uni"ue 1unordered2 pair Eu#!F of nodes in =# denoted by eDEu#!F
The nodes u and ! are called the end points of e or ad4acent nodes
or neighbors.
The edge in a graph can be directed or undirected depending on
whether the direction of the edge is specified or not.
A graph in which each edge is directed is called a directed graph or
digraph.
A graph in which each edge is undirected is called undirected graph.
A graph which contains both directed and undirected edges is called
mixed graph.
)et >D1=#$2 be a graph and e i $ be a directed edge associated with
ordered pair of !ertices 1!
<
#!
:
2. Then the edge e is said to be initiating
from !
<
to !
:
. !
<
is the starting and !
:
is the termination of the edge e.

An edge in a graph that 4oins a !ertex to itself is called a sling or a loop
The degree of a node or !ertex u is written deg1u2 is the number of edges
containing u. The degree of a loop is :
In a directed graph for any !ertex ! the number of edges which ha!e ! as their
initial !ertex is called the out-degree of #; The number of edges which ha!e !
as their terminal !ertex is called the in-degree of #. The sum of in%degree and
out%degree of a !ertex is called the degree of that !ertex. If deg1u2D;# then u is
called an isolated node and a graph containing only isolated node is called a
null graph
The maximum degree of a graph G# denoted by j1G2# is the maximum degree of
its !ertices# and the minimum degree of a graph# denoted by k1G2# is the
minimum degree of its !ertices.
A se"uence of edges of a digraph such that the terminal !ertex of the edge
se"uences in the initial !ertex of the next edge# if exist# is called a path
$D`1!
<
#!
:
2#1!
:
#!
A
2#1!
A
#!
B
2b
A path 3 of length n from a !ertex u to !ertex ! is defined as se"uence of nK<
nodes
3D1!
;
#!
<
#!
:
%%%%%%%%%%%%%%!
n
2
such that uD!
;
* !
i%<
is ad4acent to !
i
for iD<#:#A%%%%%%%%%%n* and !D!
n
.
The path is said to be closed or a circular path if !
;
D!
n
.
The path is said to be simple if all nodes are distinct# with the exception that !
;
may
e"ual !
n
* that is 3 is simple if the nodes !
;
#!
<
#!
:
%%%%%%%%!
n%<
are distinct and the nodes
!
<
#!
:
%%%%%%%%%%%%!
n
are distinct.
A cycle is closed simple path with length : or more. A cycle of length ( is called a
(%cycle.
A graph > is said to be connected if and only if there is a simple path between any
two nodes in >. In other words# a graph is connected if it does not contain any
isolated !ertices. A graph that is not connected can be di!ided into connected
components 1dis4oint connected subgraphs2. 7or example# this graph is made of
three connected components
A graph > is said to be complete if e!ery node u in > is ad4acent to e!ery node ! in
>. A complete graph with n !ertices 1denoted Vn2 is a graph with n !ertices in
which each !ertex is connected to each of the others 1with one edge between each
pair of !ertices2. In other words# there is path from e!ery !ertex to e!ery other
!ertex. Clearly such a graph is also a connected graph.
A complete graph with n nodes will ha!e n1n%<2I: edges
A connected graph without any cycles is called a tree graph or free graph or simply
a tree.
8ere are the fi!e complete graphs:
A graph is said to be labeled if its edges are assigned data. > is said to
be weighted if each edge e in > is assigned a non negati!e numerical
!alue w 1e2 called the weight or length of e.
In such a case# each path 3 in > is assigned a weight or length which
is the sum of the weights of the edges along the path 3. If no weight is
specified# it is assumed that each edge has the weight w 1e2 D<
Hultiple edges% &istinct edges e and e- are called multiple edges if
they connect the same endpoints# that is# if eDEu# !F and e-DEu# !F.
,uch edges are also called parallel edges and a graph that contains
these multiple or parallel edges is called a multigraph. Also a graph
containing loops is also not a simple graph but a multigraph.
+ire:te9 /ulti Graph
)eighte9 Graph

5epresentation of a graph%There are two main ways of representing a


graph in memory. These are:

,e"uential

)in(ed )ist

,e"uential 5epresentation% The graphs can be represented as matrices


in se"uential representation. There are two most common matrices.
These are:

Ad4acency Hatrix

Incidence Hatrix

The ad4acency matrix is a se"uence matrix with one row and one
column de!oted to each !ertex. The !alues of the matrix are ; or <. A
!alue of < for row i and column 4 implies that edge e
i4
exists between
!
i
and !
4
!ertices. A !alue of ; implies that there is no edge between
the !ertex !
i
and !
4
. Thus# for a graph with !
<
#!
:
#!
A
ccc..!
n
!ertices#
the ad4acency matrix ADEa
i4
F of the graph > is the n x n matrix and can
be defined as:
< if !
i
is ad4acent to !
4
1if there is an edge between !
i
and !
4
2
a
i4
D

; if there is no edge between !
i
and !
4

,uch a matrix that contains entries of only ; or < is called a bit matrix
or 6oolean matrix.

The ad4acency matrix of the graph > does depend on the ordering of
the nodes in > that is different ordering of the nodes may result in a
different ad4acency matrix. 8owe!er the matrices resulting from
different orderings are closely related in that one can be obtained from
another by simply interchanging rows and columns

,uppose > is an undirected graph. Then the ad4acency matrix A of >


will be a symmetric matrix i.e one in which a
i4
Da
4i
for e!ery i and 4.

If > is a multigraph# then the ad4acency matrix of > is the m x m


matrix AD1a
i4
2 defined by setting a
i4
e"ual to the number of edges from
!
i
to !
4.

Consider an Ad4acency matrix A representing a graph. Then A


:
#
A
A
cc..A
(
of Ad4acency matrix A represent the matrices with path
lengths :#Accc ( respecti!ely. In other words# if
a
(
1i#42D the i4th entry of matrix A
(

then this entry represents the number of paths of length ( from node !
i

to !
4. .
If now we represent a matrix 6
r
as
6
r
DAKA
:
KA
A
cccA
(
then each entry of 6
r
represent the number of paths of lengths r or less
than r from node !
i
to !
4
1.ample 87onsider the graph D" !uppose the nodes are stored in memor* in a linear
arra* 25T5 as follo(s8
25T58 G,H,I,/
Then (e assume that the ordering of the nodes in D as as 01JG, 02JH,03JI, 04J/" The
ad9acenc* matri. 5 of D is
0 0 0 1
5J 1 0 1 1
1 0 0 1
0 0 1 0

3ath Hatrix% )et > be a simple directed graph with m nodes#


!
<
#!
:
#!
A
ccc..!
m
. The path matrix or reachability matrix of > is the
m%s"uare matrix 3D1p
i4
2 defined as:
< if there is a path from !
i
to !
4
3
i4
D
; 'therwise
,uppose there is a path from !
i
to !
4
. Then there must be a simple
path from !
i
to !
4
when !
i
S !
4
or there must be a cycle from !
i
to !
4
when !
i
D !
4
. ,ince > has only m nodes such a simple path must be
of length m%< or less or such a cycle must ha!e length m or less.

3roposition:
)et A be the ad4acency matrix and let 3D1p
i4
2 be the path matrix of a
digraph >. Then 3
i4
D< if and only if there is a nonzero number in the
Ad4acency matrix in the i4th entry of the matrix.
6
m
D AK A
:
K A
A
Kcc. K A
m

)in(ed representation of the graph% The se"uential representation of


the graph in memory i.e the representation of graph by ad4acency
matrix has a number of ma4or drawbac(s

It may be difficult to insert and delete nodes in >raph. This is because


the size of array may need to be changed and the nodes may need to
reordered which can lead to many changes in the matrix.

Also if the number of edges are !ery less# then# the matrix will be
sparse and there will be wastage of memory.
Accordingly# graph is usually represented in memory by a
lin(ed representation also called an ad4acency structure.

,pecifically# the lin(ed representation of graph contains two lists 1or


files2# a node list +'&$ and an edge list $&>$# as follows:

+ode list% $ach element in the list +'&$ will correspond to a node in
>1>raph2 and it will be a record of the form:

8ere +'&$ will be the name or (ey !alue of the node# +$dT will
be a pointer to the next node in the list +'&$ and A&W will be a
pointer to the first element in the ad4acency list of the node# which
is maintained in the list $&>$. The last rectangle indicates that
there may be other information in the record such as indegree of
the node# the outdegree of the node# status of the node during
execution etc.

The nodes themsel!es will be maintained as a lin(ed list and


hence will ha!e a pointer !ariable ,TA5T for the beginning of the
list and a pointer !ariable A=AI)+ for the list of a!ailable space

+dge List- $ach element in the list $&>$ will correspond to an


edge of graph and will be a record of the form:


+'&$ +$dT A&W
&$,T )I+V
The field &$,T will point to the location in the list +'&$ of the
destination or terminal node of the edge. The field )I+V will lin(
together the edges with the same initial node# that is# the nodes in the
same ad4acency list. The third area indicates that there may be other
information in the record corresponding to the edge# such as a field
$&>$ containing the labeled data of the edge when graph is a
labeled graph# a field weight G$I>8T containing the weight of the
edge when graph is a weighted graph and so on.
A &
$
6 C
+ode Ad4acency )ist
A



6



C
&
$
6#C#&
C
C#$
C
Tra!ersing a >raph% There are two standard ways of tra!ersing a
graph
6readth%first search
&epth%7irst ,earch
The breadth%first search will use a "ueue as an auxiliary structure to
hold nodes for future processing# and analogously# the depth%first
search will use a stac(
&uring the execution of algorithm# each node + of > 1>raph2 will be
in one of the three states# called the status of + as follows:
,TAT/,D<: 15eady state2 The initial state of the node +
,TAT/,D:: 1Gaiting state2 The node + is one the "ueue or stac(#
waiting to be processed
,TAT/,DA: 13rocessed state2. The node + has been processed
The general idea behind a breadth%first search beginning at a starting
node A as follows:
$xamine the starting node A
$xamine all neighbors of A
Then examine all neighbors of neighbors of A and so on.
Veep trac( of neighbors of node and guarantee that no node is
processed more than once. This is accomplished by using a "ueue to
hold nodes that are waiting to be processed and by using a field
,TAT/, which tells the status of any node.
The breadth%first search algorithm helps in finding the minimum path
from source to destination node
Algorithm: This algorithm executes a breadth%first search on a graph
> beginning at a starting node A. This algorithm can
process only those nodes that are reachable from A. To
examine all the nodes in graph ># the algorithm must be
modified so that it begins again with another node that is
still in the ready state
,tep <: Initialize all nodes to the ready state 1,TAT/,D<2
,tep :: 3ut the starting node A in 9ueue and change its status to the
waiting state 1,TAT/,D:2
,tep A: 5epeat ,teps B and C until 9ueue is empty:
,tep B: 5emo!e the front node + of 9ueue. 3rocess + and change the
status of + to the processed state 1,TAT/,DA2
,tep C: Add to the rear of 9ueue all the neighbors of + that are in the
ready state 1 ,TAT/,D<2 # and change their status to the
waiting state 1,TAT/,D:2
E$nd of ,tep A )oopF
,tep J: $xit
Algorithm: This algorithm executes a depth%first search on a graph >
beginning at a starting node A. This algorithm can
process only those nodes that are reachable from A. To
examine all the nodes in graph ># the algorithm must be
modified so that it begins again with another node that is
still in the ready state
,tep <: Initialize all nodes to the ready state 1,TAT/,D<2
,tep :: 3ush the starting node A onto ,TACV and change its status to
the waiting state 1,TAT/,D:2
,tep A: 5epeat steps B and C until ,TACV is empty
,tep B: 3op the top node + of ,TACV. 3rocess + and change its status
to the processed state 1,TAT/,DA2
,tep C: 3ush onto the ,TACV all the neighbors of + that are still in the
ready state 1,TAT/,D<2 and change their status to the waiting
state 1,TAT/,D:2
E$nd of ,tep A )oopF
,tep J: $xit
Difference bet&een ,FS and DFS
The 67, uses a "ueue for its implementation whereas &7, uses a
stac(
67, is mostly used for finding the shortest distance between the two
nodes in a graph whereas &7, is mostly used to find the nodes that
are reachable from a particular node.
67, is called breadth first search as first it processes a node then its
immediate neighbors and so on. In other words# 7I7' "ueue puts all
its newly generated nodes at the end of a "ueue which means that
shallow nodes are expanded before the deeper nodes. 67, tra!erses a
graph breadth% wise. &7, first tra!erses the graph till the last
reachable node then bac( trac(s the nodes for processing. In other
words# &7, expands deepest unexpanded node first first tra!erses the
depth of the graph.
67, ensures that all the nearest possibilities are explored first whereas
&7, (eeps going as far as it can then goes bac( to loo( at other
options
&i4(stra-s Algorithm% This techni"ue is used to determine the shortest
path between two arbitrary !ertices in a graph.
)et weight w1!i #!42 is associated with e!ery edge 1!i#!42 in a gi!en
graph. 7urthermore# the weights are such that the total weight from
!ertex !i to !ertex !( through !ertex !4 is w1!i#!42 K w1!4#!(2. /sing
this techni"ue# the weight from a !ertex !s 1starting of the path2 to the
!ertex !t1 the end of the path2 in the graph > for a gi!en path 1!s#!<2#
1!<#!:2#1!:#!A2c..1!i#!t2 is gi!en by w1!s#!<2 K w1!<#!:2 Kw1!:#!A2K
c.Kw1!i#!t2
&i4(stra-s method is a !ery popular and efficient one to find e!ery
path from starting to terminal !ertices. If there is an edge between two
!ertices# then the weight of this edge is its length. If se!eral edges
exist# use the shortest length edge. If no edge actually exists# set the
length to infinity. $dge1!i#!42 does not necessarily ha!e same length
as edge 1!4#!i2. This allows different routes between two !ertices that
ta(e different paths depending on the direction of tra!el
&i4(stra-s techni"ue is based on assigning labels to each !ertex. The label is e"ual to
the distance 1weight2 from the starting !ertex to that !ertex. The starting !ertex has
the label ; A label can be in one of the two states%temporary or permanent. A
permanent label that lies along the shortest path while a temporary label is one that
has uncertainty whether the label is along the shortest path.
Algorithm:
,tep <: Assign a temporary label l1!
i
2D to all !ertices except !
s
1the starting
!ertex2
,tep :: EHar( !
s
as permanent by assigning ; label to itF
l1!
s
2D;
,tep A: EAssign !alue of !
s
to !
(
where !
(
is the last !ertex to be made permanentF
!
(
D!
s
,tep B: If l1!
i
2 N l1!
(
2 K w1!
(
#!
i
2 Eweight of the edge from !
(
to !
i
F
l1!
i
2D l1!
(
2 Kw1!
(
#!
i
2
,tep C: !
(
D!
i
,tep J: If !
t
has temporary label# repeat step B to step C otherwise the !alue of !
t
is
permanent label and is e"ual to the shortest path !
s
to !
t
,tep Z: $xit
+i;kstra<s Algorithm
An (1ample
-
2
3
6
3
=
2
6
2 -
3
6
2
3
2
Initialize
-
8

Sele:t the no9e with


the minimum temporar>
9istan:e la?el@
0p9ate Step
2
3
6
3
=
2
6
2 -
3
6
2
3
2
2
6
8

-
,hoose /inimum Temporar> %a?el
-
3
6
3
=
2
6
2 -
3
6
2
3
2
2
6
8
2

0p9ate Step
-
2
3
6
3
=
2
6
2 -
3
6
2
3
2
2
6
=
6
3
8

The pre9e:essor
of no9e 3 is now
no9e 2
,hoose /inimum Temporar> %a?el
-
2 6
3
=
2
6
2 -
3
6
2
3
2
2
3
=
6
8

3
0p9ate
-
2 6
3
=
2
6
2 -
3
6
2
3
2
8
9(3) is not :hange9@
3
2
3
=
6

,hoose /inimum Temporar> %a?el


-
2 6
=
2
6
2 -
3
6
2
3
2
8
3
2
3
=
6

3
0p9ate
-
2 6
=
2
6
2 -
3
6
2
3
2
8
3
2
3
=
6

3
9(6) is not :hange9
=
,hoose /inimum Temporar> %a?el
-
2
=
2
6
2 -
3
6
2
3
2
8
3
2
3
=
6
3
=
6
0p9ate
-
2
=
2
6
2 -
3
6
2
3
2
8
3
2
3
=
6
3
=
6
9(=) is not up9ate9
,hoose /inimum Temporar> %a?el
-
2
2
6
2 -
3
6
2
3
2
8
3
2
3
=
6
3
=
6
=
There is nothing to up9ate
(n9 of Algorithm
-
2
2
6
2 -
3
6
2
3
2
8
3
2
3
=
6
3
=
6
=
All no9es are now permanent
The pre9e:essors form a tree
The shortest path from no9e - to no9e = :an
?e foun9 ?> tra:ing ?a:k pre9e:essors

5ecursion% 5ecursion is a process by which a function calls


itself repeatedly# until some specified condition has been
satisfied. The process is used for repetiti!e computations in
which each action is stated in terms of the pre!ious result.
Hany iterati!e 1or repetiti!e2 problems can be written in this
form. In order to sol!e a problem recursi!ely# two
conditions must be satisfied

3roblem must be written in a recursi!e form

3roblem statement must include a stopping condition.

3rogram to calculate the factorial of a number using recursion


lincludeUstdio.hN
lincludeUconio.hN
!oid main12
`
int n#f*
printf1genter the numberg2*
scanf1gadg#en2*
fDfact1n2*
printf1gfactorial of the number is adg#f2*
getch12*
b
fact3int n5
`
if1nDD<2
return n*
return n] fact3n-A5H
b

Ghen a recursi!e program is executed# the recursi!e


function calls are not executed immediately. 5ather they are
placed on a stac( until the condition that terminates the
recursion is encountered. The stac( is a last%in first out data
structure in which the successi!e data items are pushed
down upon the preceding items. The data are later remo!ed
from the stac( in re!erse order.

The function calls are then executed in re!erse order as they


are popped off the stac(. Thus when e!aluating the factorial
recursi!ely# the function calls will proceed in the following
order
nmD n ] 1n%<2m
1n%<2mDn%< ] 1n%:2m
1n%:2mDn%: ] 1n%:2m
cccccc
ccccccccc
:mD: ] <m
The actual !alues returned will be in the re!erse order
<mD<
:mD : ] <mD :]<D:
AmD A ] :mD A]:DJ
BmD B ] AmDB]JD:B
%%%%%%%%%%%%%%%%%
nmDn] 1n%<2mDccc
This re!ersal in the order of execution is a characteristic of all functions
that are executed recursi!ely.
The use of recursion is not necessarily the best way to
approach a problem# e!en though the problem definition
may be recursi!e in nature. A non recursi!e implementation
may be more efficient in terms of memory utilization and
execution speed. Thus use of recursion may in!ol!e a
tradeoff between the simplicity and performance.
Program to print fibonacci series using recursion
IincludeJstdio;hK
IincludeJconio;hK
#oid main35
L
int fibbo35H
int iH
clrscr35H
for3i@AHiJMNHiOO5
printf3PQdP7fibbo3i55H
getch35H
R
int fibbo3int i5
L
if3i@@A5
L
return3N5H
R
else if3i@@B5
L
return3A5H
R
else
L
return3fibbo3i-B5Ofibbo3i-A55H
R
R
R
3rogram to find the x to the power of y using recursion
#oid main35
L
int i7 C7 resH
printf3Senter the t&o numbers as ( to the po&er yT5H
scanf3SQdQdT7Ui7UC5H
res@Po&er3i7C5H
printf3S ( to the po&er of y is QdT7res5H
getch35H
R
int Po&er1int x# int y 2
`
if1y DD ;2 return <*
y%%*
return (V Po&er3(7y5H
b
*o&ers of 9anoi- *o&ers of 9anoi is a practical application of
recursion; *he problem is as follo&s:
Suppose three pegs7 labeled A7 , and " are gi#en and suppose on
peg A there are placed a finite number n of disks &ith decreasing
si)e; *he obCect of the game is to mo#e the disks from peg A to peg
" using peg , as an au(illary; *he rules of the game are:
!nly one disk may be mo#ed one at a time;
At no time can a larger disc be placed on a smaller disk
5 B 7

,olution for towers of hanoi problem for nDA is done in se!en mo!es
as:

Ho!e top dis( from peg A to peg C

Ho!e top dis( from peg A to peg 6

Ho!e top dis( from peg C to peg 6

Ho!e top dis( from peg A to peg C

Ho!e top dis( from peg 6 to peg A

Ho!e top dis( from peg 6 to peg C

Ho!e top dis( from peg A to peg C


initial 5-K7 5-KB
7-KB
5-K7
B -K 5
B -K 7
5 -K 7
/ather than finding a separate solution for each n7 &e use the
techni:ue of recursion to de#elop a general solution

'o#e top n-A disks from peg A to peg ,

'o#e top disk from peg A to peg ": A-K"

'o#e the top n-A disks from peg , to peg ";

Let us introduce a general notation


*!?+/3N7 ,+07 A$17 +ND5
to denote a procedure &hich mo#es the top n disks from initial
peg ,+0 to final peg +ND using the peg A$1 as a au(illary;

For n@A7

*!?+/3A7 ,+07 A$17 +ND5 consist of single instruction


,+0-K+ND
For nKA7 solution may be reduced to the solution of follo&ing three
subproblems:

T'G$51+%<# 6$># $+&# A/d2

T'G$51<#6$># A/d# $+&2 6$>%N$+&

T'G$51+%<# A/d# 6$># $+&2

$ach of the three sub problems can be sol!ed directly or is essentially


the same as the original problem using fewer dis(s. Accordingly# this
reduction process does yield a recursi!e solution to the towers of
8anoi problem.

In general the recursi!e solution re"uires :


n
. < mo!es for n dis(s.

Algorithm: T'G$51+# 6$># A/d# $+&2


This procedure produces a recursi!e solution to the
Towers of 8anoi problem for + dis(s
,tep <: If +D<# then:
Grite: 6$>%N$+&
5eturn
,tep :: EHo!e + %< dis(s from peg 6$> to peg A/dF
Call T'G$51+%<# 6$># $+&# A/d2
Grite: 6$>%N$+&
,tep A: EHo!e +%< dis(s from peg A/d to peg $+&F
Call T'G$51+%<# A/d# 6$># $+&2
,tep B: 5eturn

T'G$51<#A#C#62f%%%A%N6

T'G$51:#A#6#C2 %%%%%A%NC
T'G$51<#6#A#C2 %%%%%%%%%%6%NC

T'G$51A#A#C#62%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%A%N6

T'G$51<#C#6#A2%%%%%%%%%%%%%%%% C%NA

T'G$51:#C#A#62 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%C%N6

T'G$51<#A#C#62%%%%%%%%%%%%%%%%A%N6

T'G$51B#A#6#C2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%A%NC

T'G$51<#6#A#C2 %%%%%%%%%%%%%%%%%%%6%NC

T'G$51:#6#C#A2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%6%NA
T'G$51<#C#6#A2 %%%%%%%%%%%%%%%%%%%%C%NA
T'G$51A#6#A#C2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%6%NC

T'G$51<#A#C#62 %%%%%%%%%%%%%%%%%%% A%N 6

T'G$51:#A#6#C2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%A%NC

T'G$51<#6#A#C2 %%%%%%%%%%%%%%%%%%%%6%NC
!perations on 0raph

,uppose a graph > is maintained in memory by the lin(ed list


representation

>5A381+'&$#+$dT#A&W#,TA5T#A=AI)+#&$,T#)I+V#A=AI)$2

The !arious operations possible on graph are insertion# deletion and


searching a node in a graph.

Algorithm: NSN!D+3 N!D+7 N+1*7 ADW7 S*A/*7 A>AL7 N 5



This algorithm inserts a node + in a graph >

,tep <: If A=AI):D+/))# then


Grite: M'=$57)'G-
5eturn

,tep :: E5emo!e node from A=AI) )istF


,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F

,tep B: EInsert node in the +'&$ listF


,et +'&$E+$GF:D+# A&WE+$GF:D+/))#
+$dTE+$GF:D,TA5T and ,TA5T:D+$G

,tep C: 5eturn

Algorithm: I+,$&>$1+'&$# +$dT# A&W# ,TA5T# &$,T# )I+V#


A=AI)# A #62
This algorithm inserts an edge in a graph 1A#62 where A
and 6 are the two nodes in the graph

,tep <: CA)) 7I+&1+'&$#+$dT#,TA5T#A #)'CA2

,tep :: CA)) 7I+&1+'&$# +$dT# ,TA5T# 6# )'C62

,tep A: If A=AI):D+/))# then


Grite: M'=$57)'G-
5eturn

,tep B: E5emo!e node from A=AI) )istF


,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F

,tep C: EInsert )'C6 in the list of successor of AF


,et &$,TE+$GF:D)'C6# )I+VE+$GF:DA&WE)'CAF and
A&WE)'CAF:D+$G

,tep J: 5eturn

Algorithm: 7I+& 1I+7'#)I+V#,TA5T#IT$H#)'C2


7ind the first node containing the IT$H else sets the )'C
to +/))

,tep <: ,et 3T5:D,TA5T

,tep :: 5epeat while 3T5 +/))


If IT$HDI+7'E3T5F# then
,et )'C:D3T5
5eturn
$lse
3T5D)I+VE3T5F
E$nd of )oopF

,tep A: ,et )'C:D+/))

,tep B: 5eturn
Algorithm: Algorithm to delete a node from a graph

,tep <: 7ind the location )'C of the node + in >

,tep :: &elete all edges ending at +* that is delete )'C from the list
of successors of each node H in >

,tep A: &elete all edges beginning at +. This is accomplished by


finding the location 6$> of the first successor and the location
$+& of the last successor of + and then adding the successor
list of + to the free A=AI) list

,tep B: &elete + itself from the list +'&$


Last year :uestion paper
selected :uestions

3rogram to implement 6readth 7irst search in a graph

Ge are using lin(ed list implementation of the graph


struct node
`
int info*
struct node] next*
struct edge] ad4*
b*
struct edge struct "ueue
` `
struct node] dest* struct node] n<*
struct node] lin(* struct "ueue] lin(*
b * b*
This is assumed that we ha!e a graph in which we want to apply
breadth first search to find the path from node< to node:
!oid bfs 1 struct node] node<# struct node] node:# struct node] start2
`
struct node] ptr#]item*
struct edge] edge<*
ptrDstart*
while1ptrmD+/))2
` ptr%NstatusD<*
ptrDptr%Nnext*
b
ptrDstart*
ptr%NstatusD:*
insert1ptr2*
while1frontmD+/))2
`
itemDdel12*
item%NstatusDA*
printf1ad#item%Ninfo2*
edge<Ditem%Nlin(*
while1edge<%Nlin(mD+/))2
`
if1edge<%NstatusDD<2
`
edge<%NstatusD:*
insert1edge<%Ndest2*
edge<Dedge<%Nlin(*
b
b
b


!oid insert1struct node] ptr2
` if1frontDD+/))2
`
frontDrearDptr*
return*
b
rearDrear%Nlin(*
rear%Nn<Dptr*
return*
b
struct node] del12
`
struct node] n:*
n:Dfront%Nn<*
if1frontDD+/))2
`
printf1underflow2*
return*
b
else if1frontDDrear2
`
frontDrearD+/))*
b
else
frontDfront%Nlin(*
return n:*
b

3rogram to count leaf and nonleaf nodes in a binary search tree


lincludeUstdio.hN
lincludeUconio.hN
struct tree
`
int num*
struct tree] left*
struct tree] right*
b*
struct tree] rootD+/))*
struct stac(
`
struct tree] tr*
struct stac(] lin(*
b*
struct tree] pop12*
struct stac(] topD+/))*
!oid pre12*
!oid create12*
!oid push12*
!oid main12
`
char chD@y@*
int choice#choice<*
while1chDD@y@2
`
printf1genter the type of operation <. create :. tra!ersalg2*
scanf1gadg#echoice2*
switch1choice2
`
case <: create12*
brea(*
case :: pre12*
brea(*
b
printf1gwant another operationg2*
chDgetch12*
b
getch12*
b
!oid create12
`
struct tree] new<#]ptr<#]sa!e*
if1rootDD+/))2
`
rootD1struct tree]2malloc1sizeof1struct tree22*
printf1genter the datag2*
scanf1gadg#eroot%Nnum2*
root%NleftD+/))*
root%NrightD+/))*
return*
b
ptr<Droot*
new<D1struct tree]2malloc1sizeof1struct tree22*
printf1genter the number to be addedg2*
scanf1gadg#enew<%Nnum2*
new<%NleftD+/))*
new<%NrightD+/))*
while1ptr<mD+/))2
`
if1new<%NnumUptr<%Nnum2
`sa!eDptr<*
ptr<Dptr<%Nleft*
b
else
`
sa!eDptr<*
ptr<Dptr<%Nright*
b
b
if1new<%NnumUsa!e%Nnum2
`
sa!e%NleftDnew<*
b
else
`
sa!e%NrightDnew<*
b
b
!oid pre12
`
int leafcountD;#nonleafD;*
struct tree] ptr#]temp*
ptrDroot*
while1ptrmD+/))2
`
printf1gadg#ptr%Nnum2*
if1ptr%NleftDD+/))eeptr%NrightDD+/))2
`
leafcountKK*
b
else
`
nonleafKK*
b
if1ptr%NrightmD+/))2
`
push1ptr%Nright2*
b
ptrDptr%Nleft*
b
while1topmD+/))2
`
tempDpop12*
while1tempmD+/))2
`
printf1gadg#temp%Nnum2*
if1temp%NleftDD+/))eetemp%NrightDD+/))2
`
leafcountKK*
b
else
`
nonleafKK*
b
if1temp%NrightmD+/))2
push1temp%Nright2*
tempDtemp%Nleft*
b
b
printf1gleaf nodes are ad and nonleaf nodes are adg#leafcount#nonleaf2*
b
!oid push1struct tree] p2
`
struct stac(] new<*
new<D1struct stac(]2malloc1sizeof1struct stac(22*
new<%NtrDp*
new<%Nlin(Dtop*
topDnew<*
b
struct tree] pop12
`
struct stac(] s<*
s<Dtop*
topDtop%Nlin(*
return s<%Ntr*
b

3rogram to search for an item in a binary search tree


lincludeUstdio.hN
lincludeUconio.hN
struct tree
`
int num*
struct tree] left*
struct tree] right*
b*
struct tree] rootD+/))*
struct stac(
`
struct tree] tr*
struct stac(] lin(*
b*
struct tree] pop12*
struct stac(] topD+/))*
!oid pre12*
!oid search12*
!oid create12*
!oid push12*
!oid main12
`
char chD@y@*
int choice#choice<*
while1chDD@y@2
`
printf1genter the type of operation <. create :. searchg2*
scanf1gadg#echoice2*
switch1choice2
`
case <: create12*
brea(*
case :: search12*
brea(*
b
printf1gwant another operationg2*
chDgetch12*
b
getch12*
b
!oid search12
`
int item*
struct tree] ptr#]sa!e*
printf1genter the item to be searchedg2*
scanf1gadg#eitem2*
ptrDroot*
if1rootDD+/))2
`
printf1gtree emptyg2*
return*
b
if1ptr%NnumDDitem2
`
printf1gitem foundg2*
return*
b
if1itemUptr%Nnum2
`
sa!eDptr* ptrDptr%Nleft*
b
else
` sa!eDptr* ptrDptr%Nright*
b
while1ptrmD+/))2
`
if1itemDDptr%Nnum2
`
printf1gelement foundg2*
return*
b
if1itemUptr%Nnum2
`
ptrDptr%Nleft*
b
else`ptrDptr%Nright*bb if1ptrDD+/))2
`
printf1gelement not foundg2*
return*
b
b

!oid create12
`
struct tree] new<#]ptr<#]sa!e*
if1rootDD+/))2
`
rootD1struct tree]2malloc1sizeof1struct tree22*
printf1genter the datag2*
scanf1gadg#eroot%Nnum2*
root%NleftD+/))*
root%NrightD+/))*
return*
b
ptr<Droot*
new<D1struct tree]2malloc1sizeof1struct tree22*
printf1genter the number to be addedg2*
scanf1gadg#enew<%Nnum2*
new<%NleftD+/))*
new<%NrightD+/))*
while1ptr<mD+/))2
`
if1new<%NnumUptr<%Nnum2
`sa!eDptr<*
ptr<Dptr<%Nleft*
b
else
`
sa!eDptr<*
ptr<Dptr<%Nright*
b
b
if1new<%NnumUsa!e%Nnum2
`
sa!e%NleftDnew<*
b
else
`
sa!e%NrightDnew<*
b
b

Grite an algorithm to di!ide a lin(ed list into three sublists based on a reminder
!alue of data.

Algorithm: ,ublist1 I+7' #)I+V# IT$H# ,TA5T2


This algorithm di!ides the list into three sublists based on
some reminder !alues of data. 3T5 stores the address of
current node of base list. 3T5< stores the address of current
node of first new list created and 3T5: stores the address of
current node of second sublist created.,TA5T< and
,TA5T: and ,TA5TA stores the address of the starting address of the
three sublists
,tep <: ,TA5T<:DA=AI) and A=AI):D)I+VEA=AI)F
,TA5T::DA=AI) and A=AI):D)I+VEA=AI)F
,TA5TA:DA=AI) and A=AI):D)I+VEA=AI)F
,tep :: ,et 3T5:D,TA5T# 3T5<:D,TA5T< and 3T5::D,TA5T: and
3T5A:D,TA5TA
,tep A: 5epeat while I+7'E3T5FSIT$H
I+7'E3T5F:DI+7'E3T5<F
)I+VE3T5<F:DA=AI) and A=AI):D)I+VEA=AI)F
3T5<:D)I+VE3T5<F
3T5:D)I+VE3T5F
E$nd of )oopF
,tep B: 5epeat while I+7'E3T5FSIT$H
I+7'E3T5F:DI+7'E3T5:F
)I+VE 3T5:F:DA=AI) and A=AI):D)I+VEA=AI)F
3T5::D)I+VE3T5:F
3T5:D)I+VE3T5F
E$nd of )oopF
,tep C: 5epeat while 3T5 S +/))
I+7'E3T5F:DI+7'E3T5AF
)I+VE3T5AF:DA=AI) and A=AI):D)I+VEA=AI)F
3T5A:D)I+VE3T5AF
3T5:D)I+VE3T5F
E$nd of )oopF
,tep J: $xit


3roblem: )et there be a doubly lin(ed list with three elements 3 # 9 and 5.
Grite an algorithm to insert , between 3 and 9

Grite an algorithm to delete the head element 3 from list


,ol:
1A2
Algorithm: I+,$5T1I+7'#6ACV#7'5G2
This algorithm inserts an element , between elements 3 and
9.
,tep <: I7 A=AI):D+/))# then:
Grite:-'=$57)'G-
E$nd of If structureF
,tep :: ,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F
,tep A: ,et I+7'E+$GF:D,
,tep B: ,et 3T5:D,TA5T
,tep C: 5epeat while I+7'E3T5FS3
3T5:D7'5GE3T5F
E$nd of )oopF
,tep J: ,et T$H3:D7'5GE3T5F
,et 7'5GE3T5F:D+$G
,et 6ACVE+$GF:D3T5 And 7'5GE+$GF:DT$H3
,et 6ACVET$H3F:D +$G
,tep Z: $xit

1b2 Algorithm: &el 1I+7'# 6ACV#7'5G#,TA5T2
This algorithm deletes the head node of a doubly lin(ed
list

,tep <:,et 3T5:D,TA5T

,tep :: ,et ,TA5T:D 7'5GE3T5F

,tep A: ,et 6ACVE7'5GE3T5FF:D+/))

,tep B: E5eturning memory to a!ail listF ,et 7'5GE3T5F:DA=AI)


and A=AI):D3T5

,tep C: $xit

3roblem: ,uppose the names of few students of a class are as below:


5am# ,ham# Hohan# ,ohan# =imal# Vomal
It is assumed that the names are represented as single lin(ed list
1a2 Grite a program or algorithm to insert the name 5aman between sham and mohan
1b2 Grite a routine to replace the name !imal with guman
,ol:
1a2 Algorithm: I+,5T1I+7'#)I+V#,TA5T2
This algorithm inserts an item 5aman between ,ham and Hohan
,tep <: ,et 3T5:D,TA5T
,tep :: If A=AI)D+/))
Grite: M'=$57)'G-
$xit
,tep A: ,et +$G:DA=AI) and A=AI):D)I+VEA=AI)F
,tep B: ,et I+7'E+$GF:D5aman
,tep C: 5epeat while I+7'E3T5FS,ham
3T5:D)I+VE3T5F
E$nd of )oopF
,tep J: ,et )I+VE+$GF:D)I+VE3T5F
,et )I+VE3T5F:D+$G
,tep Z:$xit

1b2 Algorithm:5eplace1I+7'#)I+V#,TA5T2
This algorithm replaces the name !imal in the lin(ed
list with name >uman. ,TA5T pointer stores the
address of starting address of the lin(ed list

,tep <: ,et 3T5:D,TA5T

,tep :: 5epeat while I+7'E3T5FS=imal


3T5:D)I+VE3T5F
E$nd of )oopF

,tep A: ,et I+7'E3T5F:D>uman

,tep B: $xit

3roblem: Calculate the depth of a tree with :;;; nodes

,olution: The formulae for calculating the depth of a tree with n


number of nodes is
&epthD )og
:
+ K <
8ere + is :;;;
7ind out the :-s power between which the !alue :;;; lies
:
<;
D<;:B and :
<<
D:;B[
Thus :;;; lies between :
<;
and :
<<
3utting in formulae
&epthD )og
:
1:
<;
to :
<<
2 K <
,electing the lower limit
D )og
:
1:
<;
2 K <
D<;)og
:
: K<
D<;K<D<<

,tatic and dynamic data structures%A static data structure in


computational complexity theory is a data structure created for an
input data set which is not supposed to change within the scope of the
problem. Ghen a single element is to be added or deleted# the update
of a static data structure incurs significant costs# often comparable
with the construction of the data structure from scratch. In real
applications# dynamic data structures are used# which allow for
efficient updates when data elements are inserted or deleted.

,tatic data structures such as arrays allow


% fast access to elements
% expensi!e to insertIremo!e elements
% ha!e fixed# maximum size
&ynamic data structures such as lin(ed lists allow
% fast insertionIdeletion of element
% but slower access to elements
% ha!e flexible size

Applications of ,inary *ree%,inary Search *ree

7or ma(ing decision trees

7or expressing mathematical expressions

7aster searching as search is reduced to half at e!ery step.

7or sorting of an array using heap sort method

7or representation of 'rganization charts

7or representation of 7ile systems

7or representation of 3rogramming en!ironments

Arithmetic $xpression Tree

n 6inary tree associated with an arithmetic expression

n internal nodes: operators

n external nodes: operands

n $xample: arithmetic expression tree for the

expression 1: o 1a p <2 K 1A o b22


Trailer node% A trailer node is li(e a header node in a lin(ed list except
that it stores the address of the last node in a lin(ed list. The
significance of this node is in a doubly lin(ed list that can be tra!ersed
in both the direction. In doubly lin(ed list# we can ta(e the ad!antage
of trailer node in searching a node in a sorted doubly lin(ed list. The
search will be more efficient.
7or con!enience# a doubly lin(ed list has a header node and a
trailer node. They are also called sentinel nodes# indicating
both the ends of a list.
header
6altimore 5ome ,eattle
trailer

&ifference from singly lin(ed lists:
% each node contains two lin(s.
% two extra nodes: header and trailer# which contain no
elements.

Вам также может понравиться