Академический Документы
Профессиональный Документы
Культура Документы
Arrays
Linked Lists
Stacks
Queues
The arrays for which we need two or more indices are (nown
as multidimensional array.
Linked List-
$ach node consists of two parts* data part and pointer or lin(
part
The whole list is accessed !ia a pointer to the first node of the
list
)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
nextPtr
.
3oints to an ob4ect of type node
.
5eferred to as a lin(
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
6inary trees
.
6inary tree can be empty without any node whereas a general tree
cannot be empty.
.
All nodes contain two lin(s
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%Ghile )oop
.
5epeat while condition:
.
E$nd of loopF
Algorithm comple(ity
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:
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.
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
The most important notation used for expressing this function f1n2 is
,ig ! notation.
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
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
!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.
,tep :: 5epeat step A and B while (UD/6 5epeat for (D)6 to /6:
to )AE(F )AE(F
,tep C: $xit
,tep C: 5eturn
,tep B: 5eturn
Analysis of Insertion and deletion operation
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.
,tep B: 5eturn
The main re"uirement of binary search method is that the array has to
be in sorted order.
Thus focus is gi!en only to the desired half of the array list.
,tep C: 5eturn
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
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 B: 5eturn
,tep C 5eturn
Accordingly#
f 1n2D 1n%<2K1n%:2K%%%%%%%%%%%%%%%%%%%%%%K:K<
D n1n%<2I:D '1n
:
2
,tep J: 5eturn
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 ::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 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
,tep [: $xit
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
f1n2Dnlogn
Herging of Arrays
,tep B: 5eturn
,tep :: 5eturn
,tep C: 5eturn
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.
,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
,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
,tep A: $xit
,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-
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
,tep J: 5eturn
Inserting into sorted )in(ed )ist
Grite: '=$57)'G
5eturn
,tep A: ,et I+7'E+$GF:D IT$H ECopies new data into new nodeF
,tep C: 5eturn
A'AI%
START
N()
%!,
-.
IT(/
Algorithm: NSS/*3NF!7LN87S*A/*7A>AL7*+'5
,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 J: 5eturn
Grite: '=$57)'G
5eturn
,tep A: ,et I+7'E+$GF:D IT$H ECopies new data into new nodeF
,tep C: 5eturn
Deletion of a node from a linked list
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 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.
,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 [: 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 B: 5eturn
"ircular Linked List-
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.
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
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.
,tep A: 5eturn
Searching a circular header linked list
Algorithm: ,5C88)1I+7'#)I+V#,TA5T#IT$H#)'C2
,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 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 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 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 C: 5eturn
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
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 B: 5eturn
Algorithm: &$)$T$1I+7'#75'G#6ACV#,TA5T#A=AI)#)'C2
This algorithm deletes a node from a two%way list
,tep B: 5eturn
,tep B: 5eturn
,A"8<P*/=
!R)"#TR$
N()
*+S* Q$+S*!NS
,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
,et I+7'E+$GF:DIT$H
,tep [: 5eturn
,tep C: 5eturn
0A/,A0+
"!LL+"*!N
&etermine what data ob4ects in a program will not be accessed in the future
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:
'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.
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
,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 B: 5eturn
,tep B: 5eturn
Application of stack
AK16]C2
1AK62I1CK&2
'perand C # mo!e to 3
2 # pop from stac( and put on 3 until 1 is encountered.
3op 1 also
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
,tep B: 5eturn
Algorithm: 9&$)$T$19/$/$#+#75'+T#5$A5#IT$H2
,tep B: 5eturn
Algorithm: 9I+,$5T19/$/$# +# 75'+T# 5$A5#IT$H2
This algorithm inserts an element in a circular "ueue
,tep B: 5eturn
Algorithm: 9&$)$T$19/$/$#+#75'+T#5$A5#IT$H2
,tep B: 5eturn
,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
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#&# ^ # ^
,tep J: 5eturn
,tep B: 5eturn
,tep C: 5eturn
*/++
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.
*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
Degree of *ree- The degree of a tree is the maximum degree of its nodes.
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
)
$D 1a%b2I11c]d2Ke2
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
,tep J: 5eturn
,tep [: 5eturn
,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.
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
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 *.
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 +
A C \ < : J [ <;
A
< C
: \
J <;
[
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*
"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 A: 5eturn
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
$xample:
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.
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.
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
,e"uential
)in(ed )ist
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
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
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.
+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.
+'&$ +$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
-
,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
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
,olution for towers of hanoi problem for nDA is done in se!en mo!es
as:
For n@A7
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#6#C2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%A%NC
T'G$51<#6#A#C2 %%%%%%%%%%%%%%%%%%%%6%NC
!perations on 0raph
>5A381+'&$#+$dT#A&W#,TA5T#A=AI)+#&$,T#)I+V#A=AI)$2
,tep C: 5eturn
,tep J: 5eturn
,tep B: 5eturn
Algorithm: Algorithm to delete a node from a graph
,tep :: &elete all edges ending at +* that is delete )'C from the list
of successors of each node H in >
!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.
,tep C: $xit
,tep B: $xit