Professional Documents
Culture Documents
DarshanInstituteofEngineering&Technology
ExplainArrayindetail
OneDimensionalArray
Simplest data structure that makes use of computed address to locate its elements is the one
dimensionalarrayorvector;numberofmemorylocationsissequentiallyallocatedtothevector.
Avectorsizeisfixedandthereforerequiresafixednumberofmemorylocations.
VectorAwithsubscriptlowerboundofoneisrepresentedasbelow.
L0
L0+(i1)C
A[i]
L0istheaddressofthefirstwordallocatedtothefirstelementof
vectorA.
Cwordsareallocatedforeachelementornode
TheaddressofAiisgivenequationLoc(Ai)=L0+C(i1)
LetsconsiderthemoregeneralcaseofrepresentingavectorA
whoselowerboundforitssubscriptisgivenbysomevariableb.
The location of Ai is then given by Loc (Ai) = L0 + C (ib)
TwoDimensionalArray
Twodimensionalarraysarealsocalledtableormatrix,twodimensionalarrayshavetwosubscripts
Twodimensionalarrayinwhichelementsarestoredcolumnbycolumniscalledascolumnmajormatrix
Twodimensionalarrayinwhichelementsarestoredrowbyrowiscalledasrowmajormatrix
Firstsubscriptdenotesnumberofrowsandsecondsubscriptdenotesthenumberofcolumns
TwodimensionalarrayconsistingoftworowsandfourcolumnsasaboveFigisstoredsequentiallyby
columns:A[1,1],A[2,1],A[1,2],A[2,2],A[1,3],A[2,3],A[1,4],A[2,4]
TheaddressofelementA[i,j]canbeobtainedbyexpressionLoc(A[i,j])=L0+(j1)*2+i1
IngeneralfortwodimensionalarrayconsistingofnrowsandmcolumnstheaddresselementA[i,j]is
givenbyLoc(A[i,j])=L0+(j1)*n+(i1)
In row major matrix, array can be generalized to arbitrary lower and upper bound in its subscripts,
assumethatb1Iu1andb2ju2
b1,b2
[1,1][1,2] [1,3]
b1,u2
[1,m ]
[2,1][2,2] [2,3]
[2m ]
[n,1][n,2] [n,3]
u1,b2
col1
col2
col3
col4
row1 [1,1]
[1,2]
[1,3]
[1,4]
row2 [2,1]
[2,2]
[2,3]
[2,4]
[n,m ]
Rowmajormatrix
Columnmajormatrix
NoofColumns=m=u2b2+1
Forrowmajormatrix:Loc(A[i,j])=L0+(ib1)*(u2b2+1)+(jb2)
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
Whatissparsematrix?Explain
AnmXnmatrixissaidtobesparseifmanyofitselementsarezero.
Amatrixthatisnotsparseiscalledadensematrix.
We can device a simple representation scheme whose space requirement equals the size of the non
zeroelements.
Example:
o Thenonzeroentriesofasparsematrixmaybemappedintoalinearlistinrowmajororder.
o Forexamplethenonzeroentriesof4X8matrixofbelowfig.(a)inrowmajororderare2,1,6,7,
3,9,8,4,5
0
Fig(a)4x8matrix
Terms
0 1 2 3 4 5 6 7 8
Row
1 1 2 2 2 3 3 4 4
Column 4 7 2 5 8 4 6 2 3
Value
2 1 6 7 3 9 8 4 5
Fig(b)LinearRepresentationofabovematrix
Toconstructmatrixstructureweneedtorecord
(a) Originalrowandcolumnsofeachnonzeroentries
(b) Noofrowsandcolumnsinthematrix
So each element of the array into which the sparse matrix is mapped need to have three fields: row,
columnandvalue
Acorrespondingamountoftimeissavedcreatingthelinearlistrepresentationoverinitializationoftwo
dimensionarray.
A=
0
0
0
0
0
0
6
0
0
12
0
0
0
7
0
0
0
3
9
8
0
0
0
0
0
0
0
0
0
0
0
4
0
0
0
5
Here from 6X7=42 elements, only 10 are non zero. A[1,3]=6, A[1,5]=9, A[2,1]=2, A[2,4]=7, A[2,5]=8,
A[2,7]=4,A[3,1]=10,A[4,3]=12,A[6,4]=3,A[6,7]=5.
One basic method for storing such a sparse matrix is to store nonzero elements in one dimensional
arrayandtoidentifyeacharrayelementswithrowandcolumnindicesfig(c).
0
2
10
0
0
0
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
1
2
3
4
5
6
7
8
9
10
ROW
1
1
2
2
2
2
3
4
6
6
ROW
1
1
2
3
3
7
4
8
5
0
6
9
ROWNO
FirstColumn
forrowno
COLUMN
3
5
1
4
5
7
1
3
4
7
Fig(c)
1
2
3
4
5
6
7
8
9
10
COLUMN
3
5
1
4
5
7
1
3
4
7
A
6
9
2
7
8
4
10
12
3
5
A
6
9
2
7
8
4
10
12
3
5
COLUMNNO
Fig(d)
A more efficient representation in terms of storage requirement and access time to the row of the
matrixisshowninfid(d).Therowvectorchangedsothatitsithelementistheindextothefirstofthe
columnindicesfortheelementinrowIofthematrix.
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
Whatisrecursion?WriteaCprogramforGCDusingrecursion.
A procedure that contains a procedure call to itself or a procedure call to second procedure which
eventuallycausesthefirstproceduretobecalledisknownasrecursiveprocedure.
Therearetwoimportantconditionsthatmustbesatisfiedbyanyrecursiveprocedure
a. Eachtimeaprocedurecallsitselfitmustbenearerinsomesensetoasolution
b. Theremustbeadecisioncriterionforstoppingtheprocessorcomputation
CprogramforGCDusingrecursion
#include<stdio.h>
int Find_GCD(int, int);
void main()
{
int n1, n2, gcd;
scanf(%d %d,&n1, &n2);
gcd = Find_GCD(n1, &n2);
printf(GCD of %d and %d is %d, n1, n2, gcd);
}
int Find_GCD(int m, int n)
{
int gcdVal;
if(n>m)
{
gcdVal = Find_GCD(n,m);
}
else if(n==0)
{
gcdVal = m;
}
else
{
gcdVal = Find_GCD(n, m%n);
}
return(gcdVal);
}
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
Givedifferencebetweenrecursionanditeration
Iteration
Initeration,aproblemisconvertedintoatrainof
stepsthatarefinishedoneatatime,oneafter
another
Withiteration,eachstepclearlyleadsontothe
next,likesteppingstonesacrossariver
Anyiterativeproblemissolvedrecursively
ItdoesnotuseStack
Recursion
Recursionislikepilingallofthosestepsontopof
eachotherandthenquashingthemallintothe
solution.
Inrecursion,eachstepreplicatesitselfatasmaller
scale,sothatallofthemcombinedtogether
eventuallysolvetheproblem.
Notallrecursiveproblemcansolvedbyiteration
ItusesStack
WritealgorithmsforStackOperationsPUSH,POP,PEEP
Alinearlistwhichallowsinsertionanddeletionofanelementatoneendonlyiscalledstack.
TheinsertionoperationiscalledasPUSHanddeletionoperationasPOP.
Themostandleastaccessibleelementsinstackareknownastopandbottomofthestackrespectively.
Sinceinsertionanddeletionoperationsareperformedatoneendofastack,theelementscanonlybe
removed in the opposite orders from that in which they were added to the stack; such a linear list is
referredtoasaLIFO(lastinfirstout)list.
ApointerTOPkeepstrackofthetopelementinthestack.Initially,whenthestackisempty,TOPhasa
valueofoneandsoon.
Each time a new element is inserted in the stack, the pointer is incremented by one before, the
elementisplacedonthestack.Thepointerisdecrementedbyoneeachtimeadeletionismadefrom
thestack.
Procedure:PUSH(S,TOP,X)
This procedure inserts an element x to the top of a stack which is represented by a vector S
containingNelementswithapointerTOPdenotingthetopelementinthestack.
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
1. [Checkforstackoverflow]
If
TOPN
Then write(STACKOVERFLOW)
Return
2. [IncrementTOP]
TOPTOP+1
3. [InsertElement]
S[TOP]X
4. [Finished]
Return
Function:POP(S,TOP)
ThisfunctionremovesthetopelementfomastackwhichisrepresentedbyavectorSandreturns
thiselement.TOPisapointertothetopelementofthestack.
1. [Checkforunderflowofstack]
If
TOP=0
Then Write(STACKUNDERFLOWONPOP)
Takeactioninresponsetounderflow
Return
2. [DecrementPointer]
TOPTOP1
3. [Returnformertopelementofstack]
Return(S[TOP+1])
Function:PEEP(S,TOP,I)
GivenavectorS(consistingofNelements)representingasequentiallyallocatedstack,andapointer
TOPdenotingthetopelementofthestack,thisfunctionreturnsthevalueoftheithelementfrom
theTOPofthestack.Theelementisnotdeletedbythisfunction.
1. [CheckforstackUnderflow]
If
TOPI+10
Then Write(STACKUNDERFLOWONPEEP)
TakeactioninresponsetoUnderflow
Exit
2. [ReturnIthelementfromtopofthestack
Return(S[TOPI+1])
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
WriteanalgorithmtochangetheithvalueofstacktovalueX
PROCEDURE:CHANGE(S,TOP,X,I)
GivenavectorS(consistingofNelements)representingasequentiallyallocatedstack,andapointer
TOPdenotingthetopelementofthestack.ThisprocedurechangesthevalueoftheIthelementfrom
thetopofthestacktothevaluecontaininginX.
1. [CheckforstackUnderflow]
If
TOPI+10
Then Write(STACKUNDERFLOWONCHANGE)
Return
2. [ChangeIthelementfromtopofthestack]
S[TOPI+1]X
3. [Finished]
Return
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
Writeanalgorithmwhichwillcheckthatthegivenstringbelongstofollowing
grammarornot.L={wcwR|w{a,b}*}(WherewRisthereverseofw)
AlgorithmRECOGNIZE
GivenaninputstringnamedSTRINGonthealphabet{a,b,c}whichcontainsablankinitsrightmost
characterpositionandfunctionNEXTCHARwhichreturnsthenextsymbolinSTRING,thisalgorithm
determineswhetherthecontentsofSTRINGbelongtotheabovelanguage.ThevectorSrepresents
thestack,andTOPisapointertothetopelementofthestack.
1. [Initializestackbyplacingaletterconthetop]
TOP1
S[TOP]c
2. [Getandstacksymbolseithercorblankisencountered]
NEXTNEXTCHAR(STRING)
RepeatwhileNEXTc
If
NEXT=
Then Write(InvalidString)
Exit
Else CallPUSH(S,TOP,NEXT)
NEXTNEXTCHAR(STRING)
3. [Scancharactersfollowingc;Comparethemtothecharactersonstack]
RepeatWhileS[TOP]c
NEXTNEXTCHAR(STRING)
XPOP(S,TOP)
If
NEXTX
Then Write(INVALIDSTRING)
Exit
4. [Nextsymbolmustbeblank]
If
NEXT
Then Write(VALIDSTRING)
Else Write(INVALIDSTRING)
5. [Finished]
Exit
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
Writeanalgorithmforpush,popandemptyoperationsonstack.Usingabove
functionswriteanalgorithmtodetermineifaninputcharacterstringisofthe
formaibiwherei>=1i.e.noofashouldbeequaltonoofb
AlgorithmRECOGNIZE
GivenaninputstringnamedSTRINGonalphabetaandbwhichcontainblank()onrightmost
characterfunctionNEXTCHARwhichreturnsthenextsymbolfromSTRING.Thisalgorithm
determinesifaninputstringisofformaibiwherei>1i.enoofashouldbeequaltonoofb.the
vectorSrepresentthestackandTOPisthepointertothetopelementofstack.Counterisacounter
Bforboccurrence.
1. [Initializestackandcounter]
TOP0
COUNTER_B0
2. [Getandstackcharacterafromwholestringandcounttheoccurrenceofb]
NEXTNEXTCHAR(STRING)
RepeatwhileNEXT!=
IF
NEXT=a
Then PUSH(S,TOP,NEXT)
Else COUNTER_BCOUNTER_B+1
NEXTNEXTCHAR(STRING)
3. [PopthestackuntilemptyanddecrementtheCOUNTERB]
RepeatwhileTOP!=0
POP(S,TOP)
COUNTER_BCOUNTER_B1
4. [Checkforgrammar]
If
COUNTER_B!=0
Then write(INVALIDSTRING)
Else write(VALIDSTRING)
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
Writeanalgorithmtoconvertinfixexpressiontopostfixexpression.
Symbol
Input precedence
Stack precedence
Rank function R
function F
function G
+, -
-1
*, /
-1
-1
Variables
Algorithm:REVPOL
GivenaninputstringINFIXcontaininganinfixexpressionwhichhasbeenpaddedontherightwith
)andwhosesymbolhaveprecedencevaluegivenbyabovetable,avectorSusedasastackanda
NEXTCHARwhichwheninvokedreturnsthenextcharacterofitsargument.Thisalgorithmconverts
INFIXintoreversepolishandplacestheresultinthestringPOLISH.TheintegervariableTOPdenotes
thetopofthestack.AlgorithmPUSHandPOPareusedforstackmanipulation.Theintegervariable
RANK accumulates the rank of expression. Finally the string variable TEMP is used for temporary
storagepurpose.
10
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
1. [Initializestack]
TOP1
S[TOP](
2. [Initializeoutputstringandrankcount]
POLISH
RANK0
3. [Getfirstinputsymbol]
NEXTNEXTCHAR(INFIX)
4. [Translatetheinfixexpression]
Repeatthrustep7whileNEXT!=
5. [Removesymbolswithgreaterprecedencefromstack]
IF
TOP<1
Then write(INVALID)
EXIT
RepeatwhileF(NEXT)<G(S[TOP])
TEMPPOP(S,TOP)
POLISHPOLISHOTEMP
RANKRANK+R(TEMP)
IF
RANK<1
Then writeINVALID)
EXIT
6. [Aretherematchingparentheses]
IF
F(NEXT)!=G(S[TOP])
Then callPUSH(S,TOP,NEXT)
Else POP(S,TOP)
7. [Getnextsymbol]
NEXTNEXTCHAR(INFIX)
8. [Istheexpressionvalid]
IF
TOP!=0ORRANK!=1
Then write(INVALID)
Else write(VALID)
11
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
Tracetheconversionofinfixtopostfixformintabularform.
(i) (A+B*C/DE+F/G/(H+I))
InputSymbol
(
A
+
B
*
C
/
D
E
+
F
/
G
/
(
H
+
I
)
)
)
Contentofstack
(
((
((
((+
((+B
((+*
((+*C
((+/
((+/D
((
((E
((+
((+F
((+/
((+/G
((+/
((+/(
((+/(H
((+/(+
((+/(+I
((+/
(
Reversepolish
A
A
AB
AB
ABC*
ABC*
ABC*D/+
ABC*D/+
ABC*D/+E
ABC*D/+E
ABC*D/+EF
ABC*D/+EF
ABC*D/+EFG/
ABC*D/+EFG/
ABC*D/+EFG/
ABC*D/+EFG/H
ABC*D/+EFG/H
ABC*D/+EFG/HI+
ABC*D/+EFG/HI+/+
ABC*D/+EFG/HI+/+
Postfixexpressionis:ABC*
Rank
0
0
0
1
1
2
2
2
2
1
1
1
1
2
2
2
2
2
3
3
3
1
1
D/+E FG/HI+/+
12
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
(ii)(A+B)*C+D/(B+A*C)+D
InputSymbol
(
A
+
B
)
*
C
+
D
/
(
B
+
A
*
C
)
+
D
)
Contentofstack
(
((
((A
((+
((+B
(
(*
(*C
(+
(+D
(+/
(+/(
(+/(B
(+/(+
(+/(+A
(+/(+*
(+/(+*C
(+/
(+
(+D
Postfixexpressionis:
Reversepolish
A
A
AB+
AB+
AB+
AB+C*
AB+C*
AB+C*D
AB+C*D
AB+C*D
AB+C*DB
AB+C*DB
AB+C*DBA
AB+C*DBA
AB+C*DBAC*+
AB+C*DBAC*+/+
AB+C*DBAC*+/+
AB+C*DBAC*+/+D+
Rank
0
0
0
1
1
1
1
1
1
1
2
2
2
3
3
4
4
3
1
1
1
AB+C*DBAC*+/+D+
13
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
Convertthefollowingstringintoprefix:AB/(C*D^E)
Step-1 : reverse infix expression
)E^)D*C((/B-A
Step-2 : convert ( to ) and ) to ( and append extra ) at last
(E^(D*C))/B-A
Step-3 : Now convert this string to postfix
InputSymbol
(
E
^
(
D
*
C
)
)
/
B
A
)
Contentofstack
(
((
((E
((^
((^(
((^(D
((^(*
((^(*C
((^
(
(/
(/B
(
(A
Reversepolish
E
E
E
ED
ED
EDC*
EDC*^
EDC*^
EDC*^
EDC*^B/
EDC*^B/
EDC*^B/A
Rank
0
0
0
1
1
1
2
2
2
1
1
1
1
1
1
Step4:Reversethispostfixexpression
A/B^*CDE
14
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
TranslatethefollowingstringintoPolishnotationandtracethecontentof
stack:(a+b^c^d)*(e+f/d)
Step-1 : reverse infix expression
)d/f+e(*)d^c^b+a(
Step-2 : convert ( to ) and ) to ( and append extra ) at last
(d/f+e)*(d^c^b+a))
Step-3 : Now convert this string to postfix
Inputsymbol
(
d
/
f
+
e
)
*
(
d
^
c
^
b
+
a
)
)
Contentofstack
(
((
((d
((/
((/f
((+
((+e
(
(+
(*(
(*(d
(*(^
(*(^c
(*(^^
(*(^^b
(*(+
(*(+a
(*
Reversepolish
d
d
df/
df/
df/e+
df/e+
df/e+
df/e+
df/e+d
df/e+d
df/e+dc
df/e+dc
df/e+dcb^^
df/e+dcb^^
df/e+dcb^^a+
df/e+dcb^^a+*
Rank
0
0
0
1
1
1
1
1
1
1
1
2
2
3
3
2
2
2
1
Step4:Reversethispostfixexpression
*+a^^bcd+e/fd
15
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
Writeanalgorithmforevaluationofpostfixexpressionandevaluationthe
followingexpressionshowingeverystatusofstackintabularform.
(i)546+*493/+*(ii)752+*411+/
Algorithm:EVALUAE_POSTFIX
Given an input string POSTFIX representing postfix expression. This algorithm is going to
evaluate postfix expression and put the result into variable VALUE. A vector S is used as
a stack PUSH and POP are the function used for manipulation of stack. Operand2 and
operand1 are temporary variable TEMP is used for temporary variable NEXTCHAR is a
function which when invoked returns the next character. PERFORM_OPERATION is a
function which performs required operation on OPERAND1 AND OPERAND2.
TEMP is DIGIT
Then
Else
16
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
Evaluate(i):546+*493/+*
EmptyStack
Readandpush
operands5,4,6
ReadOperator*,
poptwovalues
fromstackopn2=
10,opn1=5,and
pushtheanswer50
ReadOperator+,
poptwovalues
fromstackopn2=
6,opn1=4,and
pushtheanswer10
10
50 Readand
ReadOperator*,
poptwovalues
fromstackopn2=
7,opn1=50,and
pushtheanswer
350
350
push
operands
4,9,3
7
50
ReadOperator+,
poptwovalues
fromstackopn2=
3,opn1=4,and
pushtheanswer7
3
4
50
ReadOperator/,
poptwovalues
fromstackopn2=
3,opn1=9,and
pushtheanswer3
3
9
4
50
Popedvalue350istheanswer
Evaluate(ii):*752+*411+/
EmptyStack
Readandpush
operands7,5,2
ReadOperator*,
poptwovalues
fromstackopn2=
7,opn1=7,and
pushtheanswer49
ReadOperator+,
poptwovalues
fromstackopn2=
2,opn1=5,and
pushtheanswer7
49 Readand
47
ReadOperator,
poptwovalues
fromstackopn2=
2,opn1=49,and
pushtheanswer47
push
operands
4,1,1
2
49
ReadOperator/,
poptwovalues
fromstackopn2=
2,opn1=4,and
pushtheanswer2
2
4
49
ReadOperator+,
poptwovalues
fromstackopn2=
1,opn1=1,and
pushtheanswer2
1
1
4
49
Popedvalue47istheanswer
17
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
ConsiderthefollowingarithmeticexpressionP,writteninpostfixnotation.
Translateitininfixnotationandevaluate.P:12,7,3,,/,2,1,5,+,*,+
SameExpressionininfixnotationis:(12/(73))+((5+1)*2)
EmptyStack
Readandpush
operands12,7,3
ReadOperator/,
poptwovalues
fromstackopn2=
4,opn1=12,and
pushtheanswer3
ReadOperator,
poptwovalues
fromstackopn2=
3,opn1=7,and
pushtheanswer4
12
12
15
ReadOperator+,
poptwovalues
fromstackopn2=
12,opn1=3,and
pushtheanswer15
12
3
ReadOperator*,
poptwovalues
fromstackopn2=
6,opn1=2,and
pushtheanswer12
6
2
3
ReadOperator+,
poptwovalues
fromstackopn2=
5,opn1=1,and
pushtheanswer6
Readand
push
operands
2,1,5
5
1
2
3
Popedvalue15istheanswer
ExplainDifferencebetweenStackandQueue.
Stack
Queue
18
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
Stack&Queue
Explainfollowing:
(i)Queue(ii)CircularQueue(iii)DQUEUE(iv)PriorityQueue
(i)Queue
o
Alinearlistwhichpermitsdeletiontobeperformedatoneendofthelistandinsertionat
theotherendiscalledqueue.
The information in such a list is processed FIFO (first in first out) of FCFS (first
come first served) pattern.
Front is the end of queue from that deletion is to be performed.
Rear is the end of queue at which new element is to be inserted.
Front
Deletion
Insertion
Rear
(ii)CircularQueue
o Amoresuitablemethodofrepresentingsimplequeuewhichpreventsanexcessiveuseof
memory is to arrange the elements Q[1], Q[2].,Q[n] in a circular fashion with Q[1]
followingQ[n],thisiscalledcircularqueue.
(iii)Dqueue
o A dqueue (double ended queue ) is a linear list in which insertion and deletion are
performedfromtheeitherendofthestructure.
o TherearetwovariationsofDqueue
Inputrestricteddqueueallowsinsertionatonlyoneend
Outputrestricteddqueueallowsdeletionfromonlyoneend
o Suchastructurecanberepresentedbyfollowingfig.
19
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
Front
Deletion
Insertion
Insertion
Deletion
Rear
(iv)PriorityQueue
o A queue in which we are able to insert remove items from any position based on some
property(suchaspriorityofthetasktobeprocessed)isoftenreferredaspriorityqueue.
o Belowfig.representapriorityqueueofjobswaitingtouseacomputer.
o Prioritiesof1,2,3havebeenattachedwithjobsofrealtime,onlineandbatchrespectively.
Thereforeif ajobisinitiatedwithpriorityi,itisinserted immediatelyatthe endoflistof
otherjobswithprioritiesi.Herejobsarealwaysremovedfromthefrontofqueue
TaskIdentification
R1
1
R2
1
Ri1
1
O1
2
O2
2
Oj1
2
B1
3
B2
3
Bk1
3
Priority
Oj
Ri
Bk
Fig(a):PriorityQueueviewedasasinglequeuewithinsertionallowedatanyposition.
Priority1
R1 R2
Ri1
Ri
Priority2
O1 O2
Oj1
Oj
Priority3
B1 B2
Bk1
Bk
Fig(b):PriorityQueueviewedasaViewedasasetofqueue
20
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
WritealgorithmsofbasicprimitiveoperationsforQueue
Procedure:QINSERT_REAR(Q,F,R,N,Y)
GivenFandRpointerstothefrontandrearelementsofaqueue,aqueueconsistingofNelements
andanelementY,thisprocedureinsertsYattherearofthequeue.Priorstothefirstinvocationofa
procedure,FandRhavebeensettozero.
1. [Overflow]
R>=N
IF
Then write(OVERFLOW)
Return
2. [IncrementREARpointer]
RR+1
3. [Insertelement]
Q[R]Y
4. [Isfrontpointerproperlyset]
IF
F=0
Then F1
Return
Procedure:QDELETE_FRONT(Q,F,R)
Given F and R pointers to the front and rear elements of a queue and a queue Q to which they
correspond,thisfunctiondeletesandreturnsthelastelementfromthefrontendofaqueueandY
istemporaryvariable.
1. [Underflow]
IF
F=0
Then write(UNDERFLOW)
Return(0)
(0denotesanemptyQueue)
2. [Decrementelement]
YQ[F]
3. [Queueempty?]
IF
F=R
Then FR0
Else FF+1
(incrementfrontpointer)
4. [Returnelement]
Return(Y)
21
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
WritealgorithmsofbasicprimitiveoperationsforCircularQueue
Procedure:CQINSERT(F,R,Q,N,Y)
GivenpointerstothefrontandrearofacircularqueueFandR,avectorQconsistingofNelements,
andanelementY,thisprocedureinsertsYattherearofaqueue.InitiallyFandRaresettozero.
1. [ResetRearPointer]
If
R=N
Then R1
Else RR+1
2. [Overflow]
If
F=R
Then Write(Overflow)
Return
3. [Insertelement]
Q[R]Y
4. [Isfrontpointerproperlyset?]
If
F=0
Then F1
Return
FunctionCQDELETE(F,R,Q,N)
Given F and R pointers to the front and rear of a circular queue, respectively, and a vector Q
consisting of N elements, this function deletes and returns the last element of the queue. Y is a
temporaryvariable.
1. [Underflow?]
IfF=0
Then Write(UNDERFLOW)
Return(0)
2. [DeleteElement]
YQ[F]
3. [QueueEmpty?]
If
F=R
Then FR0
Return(Y)
4. [Incrementfrontpointer]
If
F=N
Then F1
Else FF+1
Return(Y)
22
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
WritealgorithmsofbasicprimitiveoperationsforDQueue
ProcedureDQINSERT_FRONT(Q,F,R,N,Y)
GivenFandRpointerstothefrontandrearelementsofaqueue,aqueueconsistingofNelements
andanelementY,thisprocedureinsertsYatthefrontofthequeue.
1. [Overflow]
IF
F=0
Then write(EMPTY)
Return
IF
F=1
Then write(OVERFLOW)
Return
2. [Decrementfrontpointer]
FF1
3. [Insertelement]
Q[F]Y
Return
ProcedureDQDELETE_REAR(Q,F,R)
GivenFandRpointerstothefrontandrearelementsofaqueue.AndaqueueQtowhichthey
correspond,thisfunctiondeletesandreturnsthelastelementfromthefrontendofaqueue.AndY
istemporaryvariable.
1. [Underflow]
IF
R=0
Then write(UNDERFLOW)
Return(0)
2. [Deleteelement]
YQ[R]
3. [Queueempty?]
IF
R=F
Then RF0
Else RR1
(decrementfrontpointer)
4. [Returnelement]
Return(Y)
23
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
Stack&Queue
DarshanInstituteofEngineering&Technology
PROCEDUREDQUEUE_DISPLAY(F,R,Q)
GivenFandRarepointerstothefrontandrearelementsofaqueue,aqueueconsistofNelements.
ThisproceduredisplayQueuecontents
1. [Checkforempty]
IF
F>=R
Then write(QUEUEISEMPTY)
Return
2. [Displaycontent]
FOR (I=FRONT;I<=REAER;I++)
Write(Q[I])
3. [ReturnStatement]
Return
Considerthefollowingqueue,wherequeueisacircularqueuehaving6
memorycells.Front=2,Rear=4
Queue:_,A,C,D,_,_
Describequeueasfollowingoperationtakeplace:
Fisaddedtothequeue
Twolettersaredeleted
Risaddedtothequeue
Sisaddedtothequeue
Oneletterisdeleted
Positions
InitialPositionofQueue,Front=2,Rear=4
Fisaddedtoqueue,Front=2,Rear=5
Twolettersaredeleted,Front=4,Rear=5
Risaddedtothequeue,Front=4,Rear=6
Sisaddedtothequeue,Front=4,Rear=1
Oneletterisdeleted,Front=5,Rear=1
S
S
2
A
A
3
C
C
4
D
D
D
D
D
F
F
F
F
F
R
R
R
24
Prof.PradyumansinhJadeja(9879461848)
|2130702DataStructure
DarshanInstituteofEngineering&Technology
LinkedList
1. Whatislinkedlist?Whataredifferenttypesoflinkedlist?OR
Writeashortnoteonsingly,circularanddoublylinkedlist.OR
Advantagesanddisadvantagesofsingly,circularanddoublylinkedlist.
Alinkedlistisacollectionofobjectsstoredinalistform.
Alinkedlistisasequenceofitems(objects)whereeveryitemislinkedtothenext.
Alinkedlistisanonprimitivetypeofdatastructureinwhicheachelementisdynamicallyallocatedand
inwhichelementspointtoeachothertodefinealinearrelationship.
Elementsoflinkedlistarecallednodeswhereeachnodecontainstwothings,dataandpointertonext
node.
Linkedlistrequiremorememorycomparedtoarraybecausealongwithvalueitstorespointertonext
node.
Linkedlistsareamongthesimplestandmostcommondatastructures.Theycanbeusedtoimplement
otherdatastructureslikestacks,queues,andsymbolicexpressions,etc
Node
info
link
Data
Pointerto
nextnode
Operationsonlinkedlist
Insert
o Insertatfirstposition
o Insertatlastposition
o Insertintoorderedlist
Delete
Traverselist(Printlist)
Copylinkedlist
Typesoflinkedlist
SinglyLinkedList
Itisbasictypeoflinkedlist.
Eachnodecontainsdataandpointertonextnode.
Lastnodespointerisnull.
Limitationofsinglylinkedlistiswecantraverseonlyinonedirection,forwarddirection.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
next
next
next
null
SinglyLinkedList
CircularLinkedList
Circularlinkedlistisasinglylinkedlistwherelastnodepointstofirstnodeinthelist.
Itdoesnotcontainnullpointerslikesinglylinkedlist.
Wecantraverseonlyinonedirectionthatisforwarddirection.
It has the biggest advantage of time saving when we want to go from last node to first node, it
directlypointstofirstnode.
Agoodexampleofanapplicationwherecircularlinkedlistshouldbeusedisatimesharingproblem
solvedbytheoperatingsystem.
next
next
next
next
CircularLinkedList
DoublyLinkedlist
Each node of doubly linked list contains data and two pointers to point previous (LPTR) and next
(RPTR)node.
Node
info
RPTR
Pointerto
previousnode
Data
Pointerto
nextnode
Mainadvantageofdoublylinkedlistiswecantraverseinanydirection,forwardorreverse.
Other advantage of doubly linked list is we can delete a node with little trouble, since we have
pointerstothepreviousandnextnodes.Anodeonasinglylinkedlistcannotberemovedunlesswe
havethepointertoitspredecessor.
Drawbackofdoublylinkedlistisitrequiresmorememorycomparedtosinglylinkedlistbecausewe
needanextrapointertopointpreviousnode.
LandRinimagedenotesleftmostandrightmostnodesinthelist.
LeftlinkofLnodeandrightlinkofRnodeisNULL,indicatingtheendoflistforeachdirection.
Prof.PradyumansinhJadeja(9879461848)
LPTR
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
null
next
prev
next
DoublyLinkedList
prev
null
2. Discussadvantagesanddisadvantagesoflinkedlistoverarray.
Advantagesofanarray
1. Wecanaccessanyelementofanarraydirectlymeansrandomaccessiseasy
2. Itcanbeusedtocreateotherusefuldatastructures(queues,stacks)
3. Itislightonmemoryusagecomparedtootherstructures
Disadvantagesofanarray
1.
2.
3.
4.
5.
Itssizeisfixed
Itcannotbedynamicallyresizedinmostlanguages
Itishardtoadd/removeelements
Sizeofallelementsmustbesame.
Rigidstructure(Rigid=Inflexibleornotchangeable)
AdvantagesofLinkedList
1. Dynamicsize
2. Itiseasytoadd/remove/changeelements
3. Elementsoflinkedlistareflexible,itcanbeprimarydatatypeoruserdefineddatatypes
DisadvantagesofLinkedList
1. Randomaccessisnotallowed.Wehavetoaccesselementssequentiallystartingfromthefirstnode.
Sowecannotdobinarysearchwithlinkedlists.
2. Itcannotbeeasilysorted
3. Wemusttraverse1/2thelistonaveragetoaccessanyelement
4. Morecomplextocreatethananarray
5. Extramemoryspaceforapointerisrequiredwitheachelementofthelist
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
Insertion&DeletionOperation
Insertionanddeletionoperationsareknownaspushandpopoperationinstackandasinsertand
deleteoperationinqueue.
Inthecaseofanarray,ifwehavenelementslistanditisrequiredtoinsertanewelementbetween
thefirstandsecondelementthenn1elementsofthelistmustbemovedsoastomakeroomfor
thenewelement.
Incaseoflinkedlist,thiscanbeaccomplishedbyonlyinterchangingpointers.
Thus,insertionanddeletionsaremoreefficientwhenperformedinlinkedlistthenarray.
Searchinganode
If a particular node in a linked list is required, it is necessary to follow links from the first node
onwardsuntilthedesirednodeisfound.
Whereasinthecaseofanarray,directlywecanaccessanynode
Join&Split
Wecanjointwolinkedlistbyassigningpointerofsecondlinkedlistinthelastnodeoffirstlinked
list.
Justassignnulladdressinthenodefromwherewewanttosplitonelinkedlistintwoparts.
Joiningandsplittingoftwoarraysismuchmoredifficultcomparedtolinkedlist.
Memory
Thepointersinlinkedlistconsumeadditionalmemorycomparedtoanarray
Size
Arrayisfixedsizedsonumberofelementswillbelimitedinstackandqueue.
Sizeoflinkedlistisdynamicandcanbechangedeasilysoitisflexibleinnumberofelements
InsertionanddeletionoperationsinArrayandLinkedList
X1 X2 X3 X4
Array
InsertYatlocation2.YouhavetomoveX2,X3,,X6
X1
X1
Linked
List
X6
X5
X2 X3
X4
X5
X2
X6
X3
X4
InsertYatlocation2.Justchangetwopointers
X1
X2
X3
X4
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
4. Writefollowingalgorithmsforsinglylinkedlist.
1)Insertatfirstposition
2)Insertatlastposition
3)InsertinOrderedLinkedlist
4)DeleteElement
Firstfewassumptions,
Unless otherwise stated, we assume that a typical element or node consists of two fields namely; an
information field called INFO and pointer field denoted by LINK. The name of a typical element is
denotedbyNODE.
Node
info
link
Data
Pointerto
nextnode
Function:INSERT(X,First)
X is new element and FIRST is a pointer to the first element of a linked linear list then this function
inserts X. Avail is a pointer to the top element of the availability stack; NEW is a temporary pointer
variable.ItisrequiredthatXprecedesthenodewhoseaddressisgivenbyFIRST.
1
[CreateNewEmptyNode]
NEWNODE
1. [Initializefieldsofnewnodeanditslinktothelist]
INFO(NEW)X
LINK(NEW)FIRST
2. [Returnaddressofnewnode]
return(NEW)
WhenINSERTisinvokeditreturnsapointervaluetothevariableFIRST
FIRSTINSERT(X,FIRST)
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
Function:INSEND(X,First)(Insertatend)
AnewelementisXandFIRSTisapointertothefirstelementofalinkedlinearlistthenthisfunction
insertsX.AVAILisapointertothetopelementoftheavailabilitystack;NEWandSAVEaretemporary
pointervariables.ItisrequiredthatXbeinsertedattheendofthelist.
1. [CreateNewEmptyNode]
NEWNODE
2. [InitializefieldofNEWnode]
INFO(NEW)X
LINK(NEW)NULL
3. [Isthelistempty?]
If
FIRST=NULL
then return(NEW)
4. [Initializesearchforalastnode]
SAVEFIRST
5. [Searchforendoflist]
RepeatwhileLINK(SAVE)NULL
SAVELINK(SAVE)
6. [SetlinkfieldoflastnodetoNEW)
LINK(SAVE)NEW
7. [Returnfirstnodepointer]
return(FIRST)
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
LinkedList
Function:INSORD(X,FIRST)
Therearemanyapplicationswhereitisdesirabletomaintainanorderedlinearlist.Theorderingis
inincreasingordecreasingorderonINFOfield.Suchorderingresultsinmoreefficientprocessing.
Thegeneralalgorithmforinsertinganodeintoanorderedlinearlistisasbelow.
1. Removeanodefromavailabilitystack.
2. Setthefieldofnewnode.
3. Ifthelinkedlistisemptythenreturntheaddressofnewnode.
4. Ifnodeprecedesallothernodesinthelisttheninsertsanodeatthefrontofthelistandreturns
itsaddress.
5. Repeat step 6 while information contain of the node in the list is less than the information
contentofthenewnode.
6. Obtainthenextnodeinthelinkedlist.
7. Insertthenewnodeinthelistandreturnaddressofitsfirstnode.
AnewelementisXandFIRSTisapointertothefirstelementofalinkedlinearlistthenthisfunction
inserts X. AVAIL is a pointer to the top element of the availability stack; NEW and SAVE are
temporarypointsvariables.ItisrequiredthatXbeinsertedsothatitpreservestheorderingofthe
termsinincreasingorderoftheirINFOfield.
1. [CreateNewEmptyNode]
NEWNODE
2. [Isthelistisempty]
If
FIRST=NULL
then LINK(NEW)NULL
return(NEW)
3. [Doesthenewnodeprecedeallothernodeinthelist?]
If
INFO(NEW)INFO(FIRST)
then LINK(NEW)FIRST
return(NEW)
4. [Initializetemporarypointer]
SAVEFIRST
5. [Searchforpredecessorofnewnode]
RepeatwhileLINK(SAVE)NULLandINFO(NEW)INFO(LINK(SAVE))
SAVELINK(SAVE)
6. [SetlinkfieldofNEWnodeanditspredecessor]
LINK(NEW)LINK(SAVE)
LINK(SAVE)NEW
7. [Returnfirstnodepointer]
return(FIRST)
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
ByrepeatedlyinvolvingfunctionINSORD,wecaneasilyobtainsanorderedlinerlistforexamplethe
sequenceofstatements.
FRONTNULL
FRONTINSORD(29,FRONT)
FRONTINSORD(10,FRONT)
FRONTINSORD(25,FRONT)
FRONTINSORD(40,FRONT)
FRONTINSORD(37,FRONT)
FRONT
29
FRONT
10
29
FRONT
10
25
29
FRONT
10
25
29
40
FRONT
10
25
29
37
40
TraceofconstructionofanorderedlinkedlinearlistusingfunctionINSORD
Procedure:DELETE(X,FIRST)
Algorithmthatdeletesnodefromalinkedlinearlist:
1. Ifalinkedlistisempty,thenwriteunderflowandreturn.
2. Repeatstep3whileendofthelisthasnotbeenreachedandthenodehasnotbeenfound.
3. Obtainthenextnodeinlistandrecorditspredecessornode.
4. Iftheendofthelisthasbeenreachedthenwritenodenotfoundandreturn.
5. Deletethenodefromlist.
6. Returnthenodeintoavailabilityarea.
A new element is X and FIRST is a pointer to the first element of a linked linear list then this
proceduredeletesthenodewhoseaddressisgivenbyX.SAVEisusedtofindthedesirednode,and
PREDkeepstrackofthepredecessorofTEMP.NotethatFIRSTischangedonlywhenXisthefirst
elementofthelist.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
1. [IsEmptylist?]
If
FIRST=NULL
then write(Underflow)
return
2. [InitializesearchforX]
SAVEFIRST
3. [FindX]
Repeatthrustep5whileSAVEXandLINK(SAVE)NULL
4. [Updatepredecessormarker]
PREDSAVE
5. [Movetonextnode]
SAVELINK(SAVE)
6. [Endofthelist]
If
SAVEX
then write(Nodenotfound)
return
7. [DeleteX]
If
X=FIRST(ifXisfirstnode?)
then FIRSTLINK(FIRST)
else LINK(PRED)LINK(X)
8. [FreeDeletedNode]
Free(X)
FunctionCOPY(FIRST)
FIRSTisapointertothefirstnodeinthelinkedlist,thisfunctionmakesacopyofthelist.
ThenewlististocontainnodeswhoseinformationandpointerfieldsaredenotedbyFIELDandPTR,
respectively.TheaddressofthefirstnodeinthenewlycreatedlististobeplacedinBEGIN.NEW,
SAVEandPREDarepointsvariables.
Ageneralalgorithmtocopyalinkedlist
1. Ifthelistisemptythenreturnnull
2. Iftheavailabilitystackisemptythenwriteavailabilitystackunderflowandreturnelsecopythe
firstnode.
3. Reportthrustep5whiletheoldlisthasnotbeenreached.
4. Obtainnextnodeinoldlistandrecorditspredecessornode.
5. If availability stack is empty then write availability stack underflow and return else copy the
nodeandaddittotherearofnewlist.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
6. Setlinkofthelastnodeinthenewlisttonullandreturn.
1. [IsEmptyList?]
If
FIRST=NULL
then return(NULL)
2. [Copyfirstnode]
NEWNODE
NewAVAIL
AVAILLINK(AVAIL)
FIELD(NEW)INFO(FIRST)
BEGINNEW
3. [Initializetraversal]
SAVEFIRST
4. [Movethenextnodeifnotattheendiflist]
Repeatthrustep6while(SAVE)NULL
5. [Updatepredecessorandsavepointer]
PREDNEW
SAVELINK(SAVE)
6. [Copynode]
If
AVAIL=NULL
then write(Availabilitystackunderflow)
return(0)
else NEWAVAIL
AVAILLINK(AVAIL)
FIELD(NEW)INFO(SAVE)
PTR(PRED)NEW
7. [Setlinkoflastnodeandreturn]
PTR(NEW)NULL
return(BEGIN)
10
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
5. Writefollowingalgorithmsforcircularlinklist
1)InsertatFirstPosition
2)InsertatLastPosition
3)InsertinOrderedLinkedList
4)DeleteElement
FUNCTION:CIRCULAR_LINK_INSERT_FIRST(X,FIRST,LAST)
A new element is X; and FIRST and LAST a pointer to the first and last element of a linked linear list
respectivelywhosetypicalnodecontainsINFOandLINKfields.AVAILisapointertothetopelementof
the availability stack; NEW is a temporary points variable. This function inserts X. It is required that X
precedesthenodewhoseaddressisgivenbyFIRST.
1. [CreateNewEmptyNode]
NEWNODE
2. [Initializefieldsofnewnodeanditslinktothelist]
INFO(NEW)X
If
FIRST=NULL
then LINK(NEW)NEW
FIRSTLASTNEW
return(FISRT)
else LINK(NEW)FIRST
LINK(LAST)NEW
FIRSTNEW
return(FIRST)
Wheninvoked,INSERTreturnsapointervaluetothevariableFIRST.
FIRSTINSERT(X,FIRST,LAST)
FUNCTION:CIR_LINK_INSERT_END(X,FIRST,LAST)
11
AnewelementisX;andFIRSTandLASTapointertothefirstandlastelementofalinkedlinear
listrespectivelywhosetypicalnodecontainsINFOandLINKfields.AVAILisapointertothetop
elementoftheavailabilitystack;NEWisatemporarypointsvariable.ThisfunctioninsertsX.It
isrequiredthatXbeinsertedattheendofthelist.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
LinkedList
1. [CreateNewEmptyNode]
NEWNODE
2. [Initializefieldsofnewnodeanditslinktothelist]
If
FIRST=NULL
then LINK(NEW)NEW
FIRSTLASTNEW
return(FIRST)
else LINK(NEW)FIRST
LINK(LAST)NEW
LASTNEW
return(FIRST)
FUNCTION:CIR_LINK_INSERT_ORDER(X,FIRST,LAST)
12
AnewelementisX;andFIRSTandLASTapointertothefirstandlastelementofalinkedlinear
listrespectivelywhosetypicalnodecontainsINFOandLINKfields.AVAILisapointertothetop
element of the availability stack; NEW and SAVE are temporary points variables. It is required
thatXbeinsertedsothatitpreservestheorderingofthetermsinincreasingorderoftheirINFO
field.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
1. [CreateNewEmptyNode]
NEWNODE
2. [Copyinformationcontentintonewnode]
INFO(NEW)X
3. [IsLinkedListisempty?]
If
FIRST=NULL
then LINK(NEW)NEW
FIRSTLASTNEW
return(FIRST)
4. [DoesnewnodeprecedesallothernodesinList?]
If
INFO(NEW)INFO(FIRST)
then LINK(NEW)FIRST
LINK(LAST)NEW
FIRSTNEW
return(FIRST)
5. [InitializeTemporaryPointer]
SAVEFIRST
6. [SearchforPredecessorofnewnode]
RepeatwhileSAVELASTandINFO(NEW)INFO(LINK(SAVE))
SAVELINK(SAVE)
7. [SetlinkfieldofNEWnodeanditsPredecessor]
LINK(NEW)LINK(SAVE)
LINK(SAVE)NEW
If
SAVE=LAST
then LASTNEW
8. [Returnfirstnodeaddress]
return(FIRST)
PROCEDURE:CIR_LINK_DELETE(X,FIRST,LAST)
13
AnewelementisX;andFIRSTandLASTapointertothefirstandlastelementofalinkedlinear
listrespectivelywhosetypicalnodecontainsINFOandLINKfields.AVAILisapointertothetop
elementoftheavailabilitystack;,thisproceduredeletesthenodewhoseaddressisgivenbyX.
TEMPisusedtofindthedesirednode,andPREDkeepstrackofthepredecessorofTEMP.Note
thatFIRSTischangedonlywhenXisthefirstelementofthelist.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
1. [IsEmptyList?]
If
FIRST=NULL
then write(LinkedListisEmpty)
return
2. [InitializeSearchforX]
TEMPFIRST
3. [FindX]
Repeatthrustep5whileSAVEXandSAVELAST
4. [Updatepredecessormarker]
PREDSAVE
5. [Movetonextnode]
SAVELINK(SAVE)
6. [EndofLinkedList]
If
SAVEX
then write(Nodenotfound)
return
7. [DeleteX]
If
X=FIRST
then FIRSTLINK(FIRST)
LINK(LAST)FIRST
else LINK(PRED)LINK(X)
If
X=LAST
then LASTPRED
8. [FreeDeletedNode]
Free(X)
14
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
6. WriteanalgorithmtoperformeachofthefollowingoperationsonCircular
singlylinkedlistusingheadernode
1)addnodeatbeginning
2)addnodeattheend
3)insertanodecontainingxafternodehavingaddressP
4)deleteanodewhichcontainelementx
FUNCTION:CIR_LINK_HEAD_INSERT_FIRST(X,FIRST,LAST)
AnewelementisX;andFIRSTandLASTapointertothefirstandlastelementofalinkedlinear
listrespectivelywhosetypicalnodecontainsINFOandLINKfields.AVAILisapointertothetop
element of the availability stack; NEW is a temporary points variable. HEAD is the address of
HEAD node. This function inserts X. It is required that X precedes the node whose address is
givenbyFIRST.
1. [CreateNewEmptyNode]
NEWNODE
2. [Initializefieldsofnewnodeanditslinktothelist]
INFO(NEW)X
LINK(NEW)LINK(HEAD)
LINK(HEAD)NEW
FUNCTION:CIR_LINK_HEAD_INSERT_LAST(X,FIRST,LAST)
AnewelementisX;andFIRSTandLASTapointertothefirstandlastelementofalinkedlinear
listrespectivelywhosetypicalnodecontainsINFOandLINKfields.Availisapointertothetop
element of the availability stack; NEW is a temporary points variable. HEAD is the address of
HEADnode.ThisfunctioninsertsX.ItisrequiredthatXbeinsertedattheendofthelist.
1. [CreateNewEmptyNode]
NEWNODE
2. [Initializefieldsofnewnodeanditslinktothelist]
INFO(NEW)X
LINK(NEW)HEAD
LINK(LAST)NEW
LASTNEW
15
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
FUNCTION:CIR_LINK_HEAD_INSERT_AFTER_NodeP(X,FIRST,LAST)
AnewelementisX;andFIRSTandLASTapointertothefirstandlastelementofalinkedlinear
listrespectivelywhosetypicalnodecontainsINFOandLINKfields.Availisapointertothetop
element of the availability stack; NEW is a temporary points variable. HEAD is the address of
HEADnode.ThisfunctioninsertsX.ItisrequiredtoinsertanodeafteranodehavingaddressP.
1. [CreateNewEmptyNode]
NEWNODE
2. [Initializefieldsofnewnodeanditslinktothelist]
INFO(NEW)X
LINK(NEW)LINK(P)
LINK(P)NEW
If
P=LAST
then LAST NEW
16
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
PROCEDURE:CIR_LINK_HEAD_DELETE(X,FIRST,LAST)
FIRSTandLASTapointertothefirstandlastelementofalinkedlinearlistrespectivelywhose
typical node contains INFO and LINK fields. Avail is a pointer to the top element of the
availabilitystack;SAVEisatemporarypointervariable.HEADistheaddressofHEADnode.This
functioninsertsX.ItisrequiredtodeleteelementhavingvalueX.
1. [IsEmptyList?]
If
FIRST=NULL
then write(Underflow)
return
2. [InitializeSearchforX]
SAVEFIRST
3. [FindX]
Repeatthrustep5whileINFO(SAVE)XandSAVELAST
4. [UpdatePredecessor]
PREDSAVE
5. [Movetonextnode]
SAVELINK(SAVE)
6. [EndoftheList]
If
INFO(SAVE)X
then write(NodenotFound)
return
7. [DeletenodeX]
If
INFO(FIRST)=X
then LINK(HEAD)LINK(FIRST)
else LINK(PRED)LINK(SAVE)
If
SAVE=LAST
then LASTPRED
8. [FreeDeletedNode]
Free(X)
17
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
7. Writefollowingalgorithmsfordoublylinklist
1)Insert
2)InsertinOrderedLinkedList
3)DeleteElement
PRDCEDUREDOUBINS(L,R,M,X)
Givenadoublylinklistwhoseleftmostandrightmostnodesaddressedaregivenbythepointer
variables L and R respectively. It is required to insert a node whose address is given by the
pointer variable NEW. The left and right links of nodes are denoted by LPTR and RPTR
respectively. The information field of a node is denoted by variable INFO. The name of an
elementofthelistisNODE.Theinsertionistobeperformedtotheleftofaspecificnodewith
its address given by the pointer variable M. The information to be entered in the node is
containedinX.
1. [CreateNewEmptyNode]
NEWNODE
2. [Copyinformationfield]
INFO(NEW)X
3. [Insertintoanemptylist]
If
R=NULL
then LPTR(NEW)RPTR(NULL)NULL
LRNEW
return
4. [Isleftmostinsertion?]
If
M=L
then LPTR(NEW)NULL
RPTR(NEW)M
LPTR(M)NEW
LNEW
return
5. [Insertinmiddle]
LPTR(NEW)LPTR(M)
RPTR(NEW)M
LPTR(M)NEW
RPTR(LPTR(NEW))NEW
return
18
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
PROCEDUREDOUBINS_ORD(L,R,M,X)
Givenadoublylinklistwhoseleftmostandrightmostnodesaddressedaregivenbythepointer
variablesLandRrespectively.Itisrequiredtoinsertanodewhoseaddressisgivenbythe
pointervariableNEW.TheleftandrightlinksofnodesaredenotedbyLPTRandRPTR
respectively.TheinformationfieldofanodeisdenotedbyvariableINFO.Thenameofan
elementofthelistisNODE.Theinsertionistobeperformedinascendingorderofinfopart.The
informationtobeenteredinthenodeiscontainedinX.
1. [CreateNewEmptyNode]
NEWNODE
2. [Copyinformationfield]
INFO(NEW)X
3. [Insertintoanemptylist]
If
R=NULL
then
LPTR(NEW)RPTR(NULL)NULL
LRNEW
return
4. [DoesthenewnodeprecedesallothernodesinList?]
If
INFO(NEW)INFO(L)
then
RPTR(NEW)L
LPTR(NEW)NULL
LPTR(L)NEW
LNEW
return
5. [InitializetopPointer]
SAVEL
6. [SearchforpredecessorofNewnode]
RepeatwhileRPTR(SAVE)NULLandINFO(NEW)INFO(RPTR(SAVE))
SAVERPTR(SAVE)
7. [Setlinkfieldofnewnodeanditspredecessor]
RPTR(NEW)RPTR(SAVE)
LPTR(RPTR(SAVE))NEW
RPTR(SAVE)NEW
LPTR(NEW)SAVE
If
SAVE=R
then
RPTR(SAVE) NEW
19
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
PROCEDUREDOUBDEL(L,R,OLD)
Givenadoublylinkedlistwiththeaddressesofleftmostandrightmostnodesaregivenbythe
pointervariablesLandRrespectively.Itisrequiredtodeletethenodewhoseaddressid
containedinthevariableOLD.NodecontainsleftandrightlinkswithnamesLPTRandRPTR
respectively.
1. [Isunderflow?]
If
R=NULL
then write(UNDERFLOW)
return
2. [Deletenode]
If
L=R(singlenodeinlist)
then LRNULL
else If
OLD=L(leftmostnode)
then LRPTR(L)
LPTR(L)NULL
else if
OLD=R(rightmost)
then RLPTR(R)
RPTR(R)NULL
else RPTR(LPTR(OLD))RPTR(OLD)
LPTR(RPTR(OLD))LPTR(OLD)
3. [Returndeletednode]
restore(OLD)
return
20
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
LinkedList
8. Writetheimplementationprocedureofbasicprimitiveoperationsofthe
stackusing:(i)Lineararray(ii)linkedlist.
Implement PUSH and POP using Linear array
#define MAXSIZE 100
int stack[MAXSIZE];
int top=-1;
void push(int val)
{
if(top >= MAXSIZE)
printf("Stack is Overflow");
else
stack[++top] = val;
}
int pop()
{
int a;
if(top>=0)
{
a=stack[top];
top-;
return a;
}
else
{
printf("Stack is Underflow, Stack is empty, nothing to POP!");
return -1;
}
}
21
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
LinkedList
22
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
LinkedList
9. Writetheimplementationprocedureofbasicprimitiveoperationsofthe
Queueusing:(i)Lineararray(ii)linkedlist
Implement Enqueue(Insert)and Dequeue(Delete)using Linear Array
# include <stdio.h>
# define MAXSIZE 100
int queue[MAXSIZE], front = -1, rear = -1;
void enqueue(int val)
{
if(rear >= MAXSIZE)
{
printf("Queue is overflow") ;
return ;
}
rear++;
queue [rear] = val;
if(front == -1)
{
front++;
}
}
int dequeue()
{
int data;
if(front == -1)
{
printf("Queue is underflow") ;
return -1;
}
data = queue [front];
if(front == rear)
{
front = rear = -1;
}
else
{
front++;
}
return data;
}
23
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
LinkedList
24
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
LinkedList
10. Writeanalgorithmtoimplementascendingpriorityqueueusing
singularlinearlinkedlistwhichhasinsert()functionsuchthatqueue
remainsorderedlist.Alsoimplementremove()function
struct node
{
int priority;
int info;
struct node *link;
}*front = NULL;
insert()
{
struct node *tmp,*q;
int added_item,item_priority;
tmp = (struct node *)malloc(sizeof(struct node));
printf("Input the item value to be added in the queue : ");
scanf("%d",&added_item);
printf("Enter its priority : ");
scanf("%d",&item_priority);
tmp->info = added_item;
tmp->priority = item_priority;
/*Queue is empty or item to be added has priority more than
first item*/
if( front == NULL || item_priority < front->priority )
{
tmp->link = front;
front = tmp;
}
else
{
q = front;
while( q->link != NULL &&
q->link->priority <= item_priority )
{
q=q->link;
}
tmp->link = q->link;
q->link = tmp;
}/*End of else*/
}/*End of insert()*/
25
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
LinkedList
DarshanInstituteofEngineering&Technology
remove()
{
struct node *tmp;
if(front == NULL)
printf("Queue Underflow\n");
else
{
tmp = front;
printf("Deleted item is %d\n",tmp->info);
front = front->link;
free(tmp);
}
}/*End of remove()*/
display()
{
struct node *ptr;
ptr = front;
if(front == NULL)
printf("Queue is empty\n");
else
{
printf("Queue is :\n");
printf("Priority Item\n");
while(ptr != NULL)
{
printf("%5d %5d\n",ptr->priority,ptr->info);
ptr = ptr->link;
}
}/*End of else */
}/*End of display() */
26
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
1. Discussfollowing
1. Graph
AgraphGconsistofanonemptysetVcalledthesetofnodes(points,vertices)ofthegraph,
asetEwhichisthesetofedgesandamappingfromthesetofedgesEtoasetofpairsof
elementsofV.
ItisalsoconvenienttowriteagraphasG=(V,E).
NoticethatdefinitionofgraphimpliesthattoeveryedgeofagraphG,wecanassociatea
pairofnodesofthegraph.IfanedgeXEisthusassociatedwithapairofnodes(U,V)
whereU,VVthenwesaysthatedgexconnectUandV.
2. AdjacentNodes
Anytwonodeswhichareconnectedbyanedgeinagrapharecalledadjacentnode.
3. Directed&UndirectedEdge
InagraphG=(V,E)anedgewhichisdirectedfromoneendtoanotherendiscalleda
directededge,whiletheedgewhichhasnospecificdirectioniscalledundirectededge.
4. Directedgraph(Digraph)
Agraphinwhicheveryedgeisdirectediscalleddirectedgraphordigraph.
5. Undirectedgraph
Agraphinwhicheveryedgeisundirectediscalleddirectedgraphordigraph.
6. MixedGraph
Ifsomeoftheedgesaredirectedandsomeareundirectedingraphthenthegraphiscalled
mixedgraph.
7. Loop(Sling)
Anedgeofagraphwhichjoinsanodetoitselfiscalledaloop(sling).
8. Multigraph
Anygraphwhichcontainssomeparalleledgesiscalledmultigraph.
9. WeightedGraph
10.
IsolatedNode
Agraphinwhichweightsareassignedtoeveryedgeiscalledweightedgraph.
Inagraphanodewhichisnotadjacenttoanyothernodeiscalledisolatednode.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
11.
NullGraph
12.
PathofGraph
13.
Thelevelofanynodeisthelengthofitspathfromtheroot.
OrderedTree
Inadirectedtree,anynodewhichhasoutdegree0iscalledterminalnodeorleftnode.
LevelofNode
21.
Adirectedtreeisanacyclicdigraphwhichhasonenodecalleditsrootwithindegree0,
whileallothernodeshaveindegree1.
Everydirectedtreemusthaveatleastonenode.
Anisolatednodeisalsoadirectedtree.
TerminalNode(LeafNode)
20.
Apathwhichoriginatesandendsinthesamenodeiscalledcycle(circuit).
DirectedTree
19.
Apathinwhichallthenodesthroughwhichittraversesaredistinctiscalledelementary
path.
Cycle(Circuit)
18.
Apathinadiagraphinwhichtheedgesaredistinctiscalledsimplepathoredgesimple.
ElementaryPath(NodeSimple)
17.
ThenoofedgeswhichhaveVastheirterminalnodeiscallasindegreeofnodeV
ThenoofedgeswhichhaveVastheirinitialnodeiscallasoutdegreeofnodeV
SumofindegreeandoutdegreeofnodeViscalleditsTotalDegreeorDegreeofvertex.
SimplePath(EdgeSimple)
16.
Thenumberofedgesappearinginthesequenceofthepathiscalledlengthofpath.
Degreeofvertex
15.
LetG=(V,E)beasimpledigraphsuchthattheterminalnodeofanyedgeinthesequenceis
theinitialnodeoftheedge,ifanyappearingnextinthesequencedefinedaspathofthe
graph.
LengthofPath
14.
Agraphcontainingonlyisolatednodesarecallednullgraph.Inotherwordssetofedgesin
nullgraphisempty.
Inadirectedtreeanorderingofthenodesateachlevelisprescribedthensuchatreeis
calledorderedtree.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
Tree
22.
Forest
23.
MaryTree
24.
Siblingsarenodesthatsharethesameparentnode.
Binarysearchtree
Iftheoutdegreeofeachandeverynodeisexactlyequalto2or0andtheirnumberof
nodesatleveliis2(i1)thenthetreeiscalledafullorcompletebinarytree.
Sibling
31.
Astrictlybinarytree(sometimesproperbinarytreeor2treeorfullbinarytree)isatreein
whicheverynodeotherthantheleaveshastwochildren.
Completebinarytree
30.
Ifinadirectedtreetheoutdegreeofeverynodeislessthanorequalto2thentreeiscalled
binarytree.
Strictlybinarytree
29.
Theheightofatreeisthelengthofthepathfromtheroottothedeepestnodeinthetree.
Binarytree
28.
Ifweconsidermarytreesinwhichthemchildrenofanynodeareassumedtohavem
distinctpositions,ifsuchpositionsaretakenintoaccount,thentreeiscalledpositionalm
arytree.
Heightofthetree
27.
Iftheoutdegreeofeachandeverynodeisexactlyequaltomor0andtheirnumberof
nodesatleveliism(i1)thenthetreeiscalledafullorcomplexmarytree.
PositionalMaryTree
26.
Ifinadirectedtreetheoutdegreeofeverynodeislessthanorequaltomthentreeis
calledanmarytree.
FullorCompleteMaryTree
25.
Ifwedeletetherootanditsedgesconnectingthenodesatlevel1,weobtainasetof
disjointtree.Asetofdisjointtreeisaforest.
Abinarysearchtreeisabinarytreeinwhicheachnodepossessedakeythatsatisfythe
followingconditions
1. Allkey(ifany)intheleftsubtreeoftherootprecedesthekeyintheroot.
2. Thekeyintherootprecedesallkey(ifany)intherightsubtree.
3. Theleftandrightsubtreesubtreesoftherootareagainsearchtrees.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
32.
HeightBalancedBinarytree(AVLTree)
AtreeiscalledAVL(heightbalancebinarytree),ifeachnodepossessesoneofthefollowing
properties
1. Anodeiscalledleftheavyifthelongestpathinitsleftsubtreeisonelongerthen
thelongestpathofitsrightsubtree.
2. Anodeiscalledrightheavyifthelongestpathintherightsubtreeisonelonger
thanpathinitsleftsubtree.
3. Anodeiscalledbalanced,ifthelongestpathinboththerightandleftsubtreeare
equal.
Themostcommonoperationsperformedontreestructureisthatoftraversal.Thisisaprocedureby
whicheachnodeinthetreeisprocessedexactlyonceinasystematicmanner.
Therearethreewaysoftraversingabinarytree.
Preorder
Preordertraversalofabinarytreeisdefinedasfollow
o Processtherootnode
o Traversetheleftsubtreeinpreorder
o Traversetherightsubtreeinpreorder
Ifparticularsubtreeisempty(i.e.,nodehasnoleftorrightdescendant)thetraversalisperformedby
doingnothing,Inotherwords,anullsubtreeisconsideredtobefullytraversedwhenitisencountered.
Preordertraversal:ABCDEFG
Inordertraversal:CBAEFDG
Postordertraversal:CBFEGDA
ConversePreordertraversal: ADGEFBC
C
Fig.1.1
E
F
ConverseInordertraversal:
GDFEABC
ConversePostordertraversal: GFEDCBA
Thepreordertraversalofatree(Fig.1.1)isgivenbyABCDEFG
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
Inorder
TheInordertraversalofabinarytreeisgivenbyfollowingsteps,
o TraversetheleftsubtreeinInorder
o Processtherootnode
o TraversetherightsubtreeinInorder
TheInordertraversalofatree(Fig.1.1)isgivenbyCBAEFDG
Postorder
Thepostordertraversalisgivenby
o Traversetheleftsubtreeinpostorder
o Traversetherightsubtreeinpostorder
o Processtherootnode
ThePostordertraversalofatree(Fig.1.1)isgivenbyCBFEGDA
Converse
Ifweinterchangeleftandrightwordsintheprecedingdefinitions,weobtainthreenewtraversalorders
whicharecalled
o ConversePreorder(ADGEFBC)
o ConverseInorder(GDFEABC)
o ConversePostorder(GFEDCBA)
3. WritethealgorithmofPreorder,InorderandPostordertraversal
techniquesofthebinarytree.
Procedure:RPREORDER(T)
GivenabinarytreewhoserootnodeaddressisgivenbypointervariableTandwhosenodestructureis
sameasdescribedbelow.Thisproceduretraversethetreeinpreorder,inarecursivemanner.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
LPTR
DATA
RPTR
1. [CheckforemptyTree]
If
T=NULL
then write(EmptyTree)
return
else write(DATA(T))
2. [ProcesstheLeftSubtree]
If
LPTR(T)NULL
then RPREORDER(LPTR(T))
3. [ProcesstheRightSubtree]
If
RPTR(T)NULL
then RPREORDER(RPTR(T))
4. [Finished]
return
Procedure:RINORDER(T)
GivenabinarytreewhoserootnodeaddressisgivenbypointervariableTandwhosenodestructureis
sameasdescribedbelow.Thisproceduretraversethetreeininorder,inarecursivemanner.
1. [CheckforemptyTree]
If
T=NULL
then write(EmptyTree)
return
2. [ProcesstheLeftSubtree]
If
LPTR(T)NULL
then RINORDER(LPTR(T))
3. [Processtherootnode]
write(DATA(T))
4. [ProcesstheRightSubtree]
If
RPTR(T)NULL
then RINORDER(RPTR(T))
5. [Finished]
return
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
Procedure:RPOSTORDER(T)
GivenabinarytreewhoserootnodeaddressisgivenbypointervariableTandwhosenodestructureis
sameasdescribedbelow.Thisproceduretraversethetreeinpostorder,inarecursivemanner.
1. [CheckforemptyTree]
If
T=NULL
then write(EmptyTree)
return
2. [ProcesstheLeftSubtree]
If
LPTR(T)NULL
then RPOSTORDER(LPTR(T))
3. [ProcesstheRightSubtree]
If
RPTR(T)NULL
then RPOSTORDER(RPTR(T))
4. [Processtherootnode]
write(DATA(T))
5. [Finished]
return
4. GivetraversalorderoffollowingtreeintoInorder,PreorderandPostorder.
Inorder:21453
Preorder:12345
Postorder:25431
1
3
4
5
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
5. ConstructatreeforthegivenInorderandPostordertraversals
Inorder
:DGBAHEICF
Postorder : G D B H I E F C A
A
HEICF
DGB
A
B
DG
HEI
A
B
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
Postorder : C B E H G I F D A
Inorder
:BCAEDGHFI
A
EDGHFI
BC
A
B
D
C
GHFI
A
B
GH
A
B
D
C
E
G
I
H
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
6. ConstructatreeforthegivenInorderandPreordertraversals
Preorder : G B Q A C K F P D E R H
Inorder : Q B K C F A G P E D H R
G
PEDHR
QBKCFA
G
B
P
KCFA
DERH
G
B
Q
P
D
A
E
KCF
RH
G
B
Q
C
K
10
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
7. Createabinarysearchtreeforthefollowingdata:
50,25,75,22,40,60,80,90,15,30
50
25
22
15
8.
75
40
80
60
30
90
ConstructbinarysearchtreeforthefollowingdataandfinditsInorder,
PreorderandPostordertraversal
10,3,15,22,6,45,65,23,78,34,5
10
3
15
6
22
45
23
65
34
78
Preorder:10,3,6,5,15,22,45,23,34,65,78
Inorder:3,5,6,10,15,22,23,34,45,65,78
Postorder:5,6,3,34,23,78,65,45,22,15,10
11
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
9. Writeashortnoteonthreadedbinarytree
ThewastedNULLlinksinthebinarytreestoragerepresentationcanbereplacedbythreads.
Abinarytreeisthreadedaccordingtoparticulartraversalorder.e.g.:Threadsfortheinordertraversals
oftreearepointerstoitshighernodes,forthistraversalorder.
o IfleftlinkofnodePisnull,thenthislinkisreplacedbytheaddressofitspredecessor.
o IfrightlinkofnodePisnull,thenitisreplacedbytheaddressofitssuccessor
Becausetheleftorrightlinkofanodecandenoteeitherstructurallinkorathread,wemustsomehow
beabletodistinguishthem.
Method1:Representthreadaveaddress.
Method2:TohaveaseparateBooleanflagforeachofleafandrightpointers,nodestructureforthisis
givenbelow,
LPTR
LTHREAD
Data
RTHREAD
RPTR
Alternatenodeforthreadedbinarytree.
LTHREAD=true=Denotesleafthreadlink
LTHREAD=false=Denotesleafstructurallink
RTHREAD=true=Denotesrightthreadedlink
RTHREAD=false=Denotesrightstructurallink
Headnodeissimplyanothernodewhichservesasthepredecessorandsuccessoroffirstandlasttree
nodes.Treeisattachedtotheleftbranchoftheheadnode
Head
Advantages
InordertraversalIfasterthanunthreadedversionastackisnotrequired.
Effectivelydeterminesthepredecessorandsuccessorforinordertraversal,forunthreadedtreethistaskis
moredifficult.
Astackisrequiredtoprovideupwardpointinginformationintreewhichthreadingprovides.
Itispossibletogeneratesuccessororpredecessorofanynodewithouthavingoverheadofstockwiththe
helpofthreading.
Disadvantages
Threadedtreesareunabletosharecommonsubtrees
Ifveaddressingisnotpermittedinprogramminglanguage,twoadditionalfieldsarerequired.
12
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
Insertionintoanddeletionfromthreadedbinarytreearemoretimeconsumingbecauseboththreadand
structurallinkmustbemaintained.
A
E
C
F
BinaryTree
InorderTraversalCBAEFDG
FullyInthreadedbinarytreeofgivenbinarytree
HEAD
B
C
D
E
13
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
10.
Drawarightinthreadedbinarytreeforthegiventree
RightInthreadedbinarytreeofgivenbinarytree
HEAD
B
C
14
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
11. Whatisthemeaningofheightbalancedtree?Howrebalancingisdonein
heightbalancedtree.
AtreeiscalledAVL(heightbalancebinarytree),ifeachnodepossessesoneofthefollowingproperties
1. Anodeiscalledleftheavyifthelongestpathinitsleftsubtreeisonelongerthenthelongestpathofits
rightsubtree.
2. Anodeiscalledrightheavyifthelongestpathintherightsubtreeisonelongerthanpathinitsleftsub
tree.
3. Anodeiscalledbalanced,ifthelongestpathinboththerightandleftsubtreeareequal.
Iftreebecomesunbalancedbyinsertinganynode,thenbasedonpositionofinsertion,weneedtorotatethe
unbalancednode.Rotationistheprocesstomaketreebalanced
1)
2)
3)
4)
InsertionintoLeftsubtreeofnodesLeftchildSingleRightRotation
InsertionintoRightsubtreeofnodesLeftchildLeftRightRotation
InsertionintoLeftsubtreeofnodesRightchildRightLeftRotation
InsertionintoRightsubtreeofnodesRightchildSingleLeftRotation
1) InsertionintoLeftsubtreeofnodesLeftchildSingleRightRotation
IfnodebecomesunbalancedafterinsertionofnewnodeatLeftsubtreeofnodesLeftchild,thenweneed
toperformSingleRightRotationforunbalancednode.
RightRotation
a. Detachleafchildsrightsubtree
b. Considerleafchildtobethenewparent
c. Attacholdparentontorightofnewparent
d. Attacholdleafchildsoldrightsubtreeasleafsubtreeofnewrightchild
CriticalNode
K
X
15
Prof.PradyumansinhJadeja(9879461848)
Right
Rotation
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
13
CriticalNode
Stepsof
Right
Rotation
15
10
13
15
10
3
7
13
5
5
13
3
10
15
10
15
2) InsertionintoRightsubtreeofnodesLeftchildLeftRightRotation
IfnodebecomesunbalancedafterinsertionofnewnodeatRightsubtreeofnodesLeftchild,thenweneed
toperformLeftRightRotationforunbalancednode.
Leafrotationofleafchildfollowedbyrightrotationofparent
J
K
X
Right
RotationofJ
K
Left
RotationofK
3) InsertionintoLeftsubtreeofnodesRightchildRightLeftRotation
IfnodebecomesunbalancedafterinsertionofnewnodeatLeftsubtreeofnodesRightchild,thenwe
needtoperformRightLeftRotationforunbalancednode.
Singlerightrotationofrightchildfollowedbyleftrotationofparent
16
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
Unbalancednode
X
T1
Right
RotationofZ
Left
RotationofX
T1
T2
T4
Z
T1
T3
T2
T2
T3
T4
T4
T3
4) InsertionintoRightsubtreeofnodesRightchildSingleLeftRotation
IfnodebecomesunbalancedafterinsertionofnewnodeatRightsubtreeofnodesRightchild,thenwe
needtoperformSingleLeftRotationforunbalancednode.
LeftRotation
a. Detachrightchildsleafsubtree
b. Considerrightchildtobenewparent
c. Attacholdparentontoleftofnewparent
d. Attacholdrightchildsoldleftsubtreeasrightsubtreeofnewleftchild
X Unbalancednode
T1
Leaf
RotationofX
T3
T3
T2
T1
T2
Example
50
40
Unbalancednode
70
70
70
50
50
80
80
90
60
80
90
40
90
40
60
60
17
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
12. ConstructAVLSearchtreebyinsertingfollowingelementsinorderof
theiroccurrence6,5,4,3,2,1
1
Insert6
Insert:5
Insert :4
4
Insert:3
Right
Rotate6
5
5
4
5
5
Insert:2
Insert:1
Righ
3
2
6
2
4
Right
Rotate5
Rotate4
3
2
3
2
1
5
4
Assignment:
Defineheightofthebinarytree.Defineheightbalancedtreewithitsadvantages.Constructaheight
balancedbinarytree(AVLtree)forthefollowingdata42,06,54,62,88,50,22,32,12,33
ConstructtheAVLsearchtreebyinsertingthefollowingelementsintheorderoftheiroccurrence.64,1,
44,26,13,110,98,85
18
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
13. WhataretheadvantagesofMultiwaysearchtreeindiscaccess?
ConstructBtreeoforder5forthefollowingdata
1,7,6,2,11,5,10,13,12,20,16,24,3,4,18,19,14,25
Insert:1
Insert:6
Insert:7
1,6
Insert:2
Insert:11
6
1,6,7
1,2,6,7
1,2,6,7,11
1,2
Overflow
7,11
6
Insert:5
Insert:10
Insert:13
1,2,5
7,11
1,2,5
6
7,10,11
1,2,5
7,10,11,13
10
Insert:12
Insert:20
6
6,11
1,2,5
7,10,11,12,13
7,10
1,2,5
6,11
12,13
1,2,5
7,10
12,13,20
Overflow
11
12
Insert:16
Insert:24
6,11
6,11
6,11,16
1,2,5
7,10
12,13,16,20
1,2,5
7,10
12,13,16,20,24
Overflow
1,2,5
7,10
12,13
20,24
24,25
19
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
13
Insert:3,4
361116
6,11,16
1,2,3,4,5
7,10
12,13
20,24
4,5
1,2
12,13
7,10
20,24
Overflow
14
Insert:18,19,14
361116
4,5
1,2
7,10
12,13,14
18,19,20,24
12,13,14
18,19,20,24,25
15
Insert:25
361116
1,2
4,5
7,10
Overflow
11
3,6
1,2
4,5
16,20
7,10
12,13,14
18,19
24,25
Assignment:
Constructmutiwaysearchtreeforthefollowingdataoforderfor100,150,50,55,250,200,170,65,75,
20,30,52,10,25,180,190,300,5
20
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
14.
Whatis23tree?
A23treeisatypeofdatastructure,whereeverynodewithchildrenhaseithertwochildrenorthreechildren.
Everynonleafisa2nodeora3node.
Allleavesareatthesamelevel(thebottomlevel)
Alldataarekeptinsortedorder
Everynonleafnodewillcontain1or2fields
15. Whatisgraph?Howitcanberepresentedusingadjacencymatrix,what
ispathmatrix?Howpathmatrixcanbefoundoutusingadjacencymatrix.
Graph
AgraphGconsistofanonemptysetVcalledthesetofnodes(points,vertices)ofthegraph,asetE
whichisthesetofedgesandamappingfromthesetofedgesEtoasetofpairsofelementsofV.
ItisalsoconvenienttowriteagraphasG=(V,E).
NoticethatdefinitionofgraphimpliesthattoeveryedgeofagraphG,wecanassociateapairofnodes
ofthegraph.IfanedgeXEisthusassociatedwithapairofnodes(U,V)whereU,VVthenwesays
thatedgexconnectUandV.
Adjacencymatrix
LetG=(V,E)beasimplediagraphinwhichV={v1,v2,.,vn}andthenodesareassumedtobeorderedfrom
v1tovn.AnnxnmatrixAwhoseelementsareaijaregivenby
aij=
1
0
iscalledadjacencymatrixofthegraphG.
Anyelementoftheadjacencymatrixiseither0or1.
ForagivengraphG=m(V,E),anadjacencymatrixdependsupontheorderingoftheelementsofV.
FordifferentorderingoftheelementsofVwegetdifferentadjacencymatrices.
V1
V4
V2
V3
V1
V2
V3
V4
V1
0
1
1
0
Adigraphanditsadjacencymatrix
21
Prof.PradyumansinhJadeja(9879461848)
V2
1
0
1
1
V3
0
0
0
0
V4
1
0
1
0
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
Wecanextendtheideaofmatrixrepresentationtomultigraphsandweightedgraphs.Inthecaseof
multigraphorweightedgraphwewriteaji=w,whereaijdenoteseitherthemultiplicityittheweightof
theedge.
Pathmatrix
Anentryof1intheithrowandjthcolumnofAshowstheexistenceofanedge(vi,vj),thatisapath
oflength1fromvitovj.
LetdenotetheelementsofA2byaij(2).Then
(2)
Thereforeaij isequaltothenumberofdifferentpathsofexactlylength2fromvitovj.
SimilarlyelementinithrowandjthcolumnofA3givesnumberofpathsofexactlylength3fromvito
vj.
1
A = 0
1
1
1
1
2
1
0
0
0
0
0
1
1
0
A =
1
1
2
0
1
1
2
1
0
0
0
0
1
0
1
1
A =
1
1
2
1
2
1
3
1
0
0
0
0
1
1
2
0
Differentpathmatrices
16. WhicharethebasictraversingtechniquesoftheGraph?Writethe
algorithmofthem.
Mostgraphproblemsinvolvetraversalofagraph.Traversalofagraphmeansvisiteachnodeexactly
once.
Twocommonlyusedgraphstraversaltechniquesare
1. DepthFirstSearch(DFS)
2. BreadthFirstSearch(BFS)
DepthFirstSearch(DFS)
Itislikepreordertraversaloftree.
Traversalcanstartfromanyvertexvi
ViisvisitedandthenallverticesadjacenttoviaretraversedrecursivelyusingDFS
22
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
DFS(G,1)isgivenby
5
a) Visit(1)
b) DFS(G,2)
DFS(G,3)
DFS(G,4)
DFS(G,5)
DFStraversalofgivengraphis:
1,2,6,3,8,7,4,5
GraphG
Sincegraphcanhavecycles,wemustavoidrevisitinganode.TodothiswhenwevisitavertexV,
wemarksitvisitedasvisitedshouldnotbeselectedfortraversal.
Procedure:DFS(vertecxV)
This procedure traverse the graph G in DFS manner. V is a starting vertex to be explored. S is a
Stack, visited[] is an array which tells you whether particular vertex is visited or not. W is a
adjacent node of vertex V. PUSH and POP are functions to insert and remove from stack
respectively.
1. [InitializeTOPandVisited]
visited[]0
TOP0
2. [Pushvertexintostack]
PUSH(V)
3. [Repeatwhilestackisnotempty]
Repeatstep3whilestackisnotempty
vPOP()
if
visited[v]is0
then visited[v]1
forallWadjacenttov
if
visited[v]is0
then PUSH(W)
endfor
endif
23
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
BreadthFirstSearch(BFS)
Thismethodsstartsfromvertexv0
V0ismarkedasvisited.Allverticesadjacenttov0arevisitednext
Letverticesadjacenttov0arev1,v2,v3,v4
v1,v2,v3andv4aremarkedvisited.
Allunvisitedverticesadjacenttov1,v2,v3,v4arevisitednext.
Themethodcontinuousuntilallverticesarevisited
ThealgorithmforBFShastomaintainalistofverticeswhichhavebeenvisitedbutnotexploredfor
adjacentvertices.Theverticeswhichhavebeenvisitedbutnotexploredforadjacentverticescanbe
storedinqueue.
Initiallythequeuecontainsthestartingvertex.
Ineveryiteration,avertexisremovedfromthequeueanditsadjacentverticeswhicharenotvisited
asyetareaddedtothequeue.
Thealgorithmterminateswhenthequeuebecomesempty.
1
GraphG
2
BFStraversalofgivengraphis:
1|2,3,4,5|6,7|8
7
Procedure:BFS(VertexV)
This procedure traverse the graph G in BFS manner. V is a starting vertex to be explored. Q is a
queue, visited[] is an array which tells you whether particular vertex is visited or not. W is a
adjacentnodeofvertexV.
1. InitializeQ
2. [MarksvisitedofVas1]
visited[v]1
3. [AddvertexvtoQ]
InsertQueue(V)
4. [RepeatwhileQisnotempty]
RepeatwhileQisnotempty
vRemoveFromQueue()
ForallverticesWadjacenttov
if
visited[w]is0
then visited[w]1
InsertQueue(w)
24
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
17.
Whatisspanningtree?
ASpanningtreeofagraphisanundirectedtreeconsistingofonlythoseedgesnecessarytoconnectall
thenodesintheoriginalgraph
Aspanningtreehasthepropertiesthat
o Foranypairofnodesthereexistsonlyonepathbetweenthem
o Insertionofanyedgetoaspanningtreeformsauniquecycle
TheparticularSpanningforagraphdependsonthecriteriausedtogenerateit.
IfDFSsearchisuse,thoseedgestraversedbythealgorithmformstheedgesoftree,referredtoas
DepthFirstSpanningTree.
IfBFSSearchisused,thespanningtreeisformedfromthoseedgestraversedduringthesearch,
producingBreadthFirstSearchSpanningtree.
V0
V2
V1
V3
V4
V5
V6
V7
V0
V0
V3
V4
V5
V2
V1
V2
V1
V6
V7
DFSSpanningTree
V3
V4
V5
V6
V7
BFSSpanningTree
25
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
18. ConsiderthegraphshowninFigFinddepthfirstandbreadthfirst
traversalsofthisgraphstartingatA
C
E
D
A
C
E
D
DFS:ABDCFE
E
D
F
BFS:ABCDFE
26
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
19. Definespanningtreeandminimumspanningtree.Findtheminimum
spanningtreeofthegraphshowninFig.
A
4
3
6
5
UsingPrimsAlgorithm:
LetXbethesetofnodesexplored,initiallyX={A}
Step1:TakingminimumweightedgeofallAdjacent
edgesofX={A}
Step2:TakingminimumweightedgeofallAdjacent
edgesofX={A,B}
X={A,B}
X={A,B,C}
C
Step3:TakingminimumweightedgeofallAdjacent
edgesofX={A,B,C}
Step4:TakingminimumweightedgeofallAdjacent
edgesofX={A,B,C,D}
B
X={A,B,C,D}
AB|4
AE|5
AC|6
AD|6
BE|3
BC|2
CE|6
CD|1
DE|7
X={A,B,C,D,E}
AllnodesofgrapharetherewithsetX,soweobtainedminimumspanningtreeofcost:4+2+1+3=10
27
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
4
3
UsingKruskalsAlgorithm
6
5
Step1:Takingminedge(C,D)
Step2:Takingnextminedge(B,C)
Step3:Takingnextminedge(B,E)
B
2
Alledgesofgraphhasbeenvisited,
soweobtainedminimumspanningtreeofcost:
4+2+1+3=10
Step5:Takingnextminedge(A,E)itformscyclesodonotconsider
Step6:Takingnextminedge(C,E)itformscyclesodonotconsider
Step7:Takingnextminedge(A,D)itformscyclesodonotconsider
Step8:Takingnextminedge(A,C)itformscyclesodonotconsider
Step9:Takingnextminedge(E,D)itformscyclesodonotconsider
Step4:Takingnextminedge(A,B)
20. Giveexampleandapplicationsofdirectedandundirectedgraphs.Find
theadjacencymatrixforthegraphshowninFig.
Adjacencymatrixforthegivengraph
1
6
2
1
2
3
4
5
6
1
0
0
1
0
0
1
2
1
0
0
0
0
0
3
0
0
0
1
1
1
4
0
1
0
0
0
0
5
0
0
0
1
0
0
6
0
0
0
0
1
0
28
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
Tree
Applicationsofgraph:
ElectronicCircuits
o PrintedCircuitBoard
o IntegratedCircuit
Transportationnetworks
o Highwaynetworks
Modelingaroadnetworkwithvertexesastownsandedgecostsasdistances.
o WaterSupplynetworks
Modelingawatersupplynetwork.Acostmightrelatetocurrentorafunctionofcapacityand
length.Aswaterflowsinonly1direction,fromhighertolowerpressureconnectionsor
downhill,suchanetworkisinherentlyanacyclicdirectedgraph.
o Flightnetwork
Minimizingthecostandtimetakenforairtravelwhendirectflightsdon'texistbetweenstarting
andendingairports.
Computernetworks
o LocalAreaNetwork
o Internet
Dynamicallymodelingthestatusofasetofroutesbywhichtrafficmightbedirectedoverthe
Internet.
o Web
Usingadirectedgraphtomapthelinksbetweenpageswithinawebsiteandtoanalyzeeaseof
navigationbetweendifferentpartsofthesite.
Databases
o EntityRelationshipDiagram
29
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Tree
DarshanInstituteofEngineering&Technology
21. ApplyDijkstrasalgorithmtofindshortestpathbetweenvertexAand
vertexF5forthegraphshowninFig.
2
1
3
F
2
Step1:TraversealladjacentnodeofA
Step2:TraversealladjacentnodeofB
1
2
1
0
A
3
D
4
D
4
1
3
6
7
6
7
A
3
D
4
1
3
6
7
D
4
Step4:TraversealladjacentnodeofD
3
Step3:TraversealladjacentnodeofC
6
7
2
E
5
5
Step5:TraversealladjacentnodeofE
3
1
0
1
3
3
6
7
ShortestpathfromnodeAtoFis:
ABEFasshowninstep5
Lengthofpathis7
E
5
30
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Hashing
DarshanInstituteofEngineering&Technology
WhatisHashing?
Sequential search requires, on the average O(n) comparisons to locate an element. So many
comparisonsarenotdesirableforalargedatabaseofelements.
Binary search requires much fewer comparisons on the average O (log n) but there is an additional
requirement that the data should be sorted. Even with best sorting algorithm, sorting of elements
require0(nlogn)comparisons.
There is another widely used technique for storing of data called hashing. It does away with the
requirement of keeping data sorted (as in binary search) and its best case timing complexity is of
constantorder(0(1)).Initsworstcase,hashingalgorithmstartsbehavinglikelinearsearch.
Bestcasetimingbehaviorofsearchingusinghashing=O(1)
WorstcasetimingBehaviorofsearchingusinghashing=O(n)
Inhashing,therecordforakeyvalue"key",isdirectlyreferredbycalculatingtheaddressfromthekey
value. Address or location of an element or record, x, is obtained by computing some arithmetic
functionf.f(key)givestheaddressofxinthetable.
Record
0 1 2 3 45 6
f()Address
MappingofRecordinhashtable
HashTable
HashTableDataStructure:
Therearetwodifferentformsofhashing.
1. Openhashingorexternalhashing
Openorexternalhashing,allowsrecordstobestoredinunlimitedspace(couldbeaharddisk).Itplaces
nolimitationonthesizeofthetables.
2. Closehashingorinternalhashing
Closedorinternalhashing,usesafixedspaceforstorageandthuslimitsthesizeofhashtable.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Hashing
DarshanInstituteofEngineering&Technology
1. OpenHashingDataStructure
buckettable
header
ListofElements
B1
Theopenhashingdataorganization
Thebasicideaisthattherecords[elements]arepartitionedintoBclasses,numbered0,1,2Bl
AHashingfunctionf(x)mapsarecordwithkeyntoanintegervaluebetween0andBl.
Eachbucketinthebuckettableistheheadofthelinkedlistofrecordsmappedtothatbucket.
2. CloseHashingDataStructure
0
2
3
Aclosedhashtablekeepstheelementsinthebucketitself.
Onlyoneelementcanbeputinthebucket
Ifwetrytoplaceanelementinthebucketf(n)andfinditalreadyholds
anelement,thenwesaythatacollisionhasoccurred.
Incaseofcollision,theelementshouldberehashedtoalternateempty
locationf1(x),f2(x),...withinthebuckettable
Inclosedhashing,collisionhandlingisaveryimportantissue.
HashingFunctions
CharacteristicsofaGoodHashFunction
Agoodhashfunctionavoidscollisions.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
Hashing
Agoodhashfunctiontendstospreadkeysevenlyinthearray.
Agoodhashfunctioniseasytocompute.
Differenthashingfunctions
1.
2.
3.
4.
5.
6.
7.
DivisionMethod
MidsquareMethods
FoldingMethod
DigitAnalysis
LengthDependentMethod
AlgebraicCoding
MultiplicativeHashing
1. DivisionMethod
Inthismethodweusemodulararithmeticsystemtodividethekeyvaluebysomeintegerdivisorm
(maybetablesize).
Itgivesusthelocationvalue,wheretheelementcanbeplaced.
Wecanwrite,
L=(Kmodm)+1
whereL=>locationintable/file
K=>keyvalue
m=>tablesize/numberofslotsinfile
Suppose, k=23,m=10then
L=(23mod10)+1=3+1=4,Thekeywhosevalueis23isplacedin4thlocation.
2. MidsquareMethods
Inthiscase,wesquarethevalueofakeyandtakethenumberofdigitsrequiredtoformanaddress,
fromthemiddlepositionofsquaredvalue.
Supposeakeyvalueis16,thenitssquareis256.Nowifwewantaddressoftwodigits,thenyou
selecttheaddressas56(i.e.twodigitsstartingfrommiddleof256).
3. FoldingMethod
Most machines have a small number of primitive data types for which there are arithmetic
instructions.
Frequentlykeytobeusedwillnotfiteasilyintooneofthesedatatypes
Itisnotpossibletodiscardtheportionofthekeythatdoesnotfitintosuchanarithmeticdatatype
Thesolutionistocombinethevariouspartsofthekeyinsuchawaythatallpartsofthekeyaffect
forfinalresultsuchanoperationistermedfoldingofthekey.
Thatisthekeyisactuallypartitionedintonumberofparts,eachparthavingthesamelengthasthat
oftherequiredaddress.
Addthevalueofeachparts,ignoringthefinalcarrytogettherequiredaddress.
Thisisdoneintwoways:
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
Hashing
Foldshifting:Hereactualvaluesofeachpartsofkeyareadded.
Suppose,thekeyis:12345678,andtherequiredaddressisoftwodigits,
Thenbreakthekeyinto:12,34,56,78.
Addthese,weget12+34+56+78:180,ignorefirst1weget80aslocation
Foldboundary:Herethereversedvaluesofouterpartsofkeyareadded.
Suppose,thekeyis:12345678,andtherequiredaddressisoftwodigits,
Thenbreakthekeyinto:21,34,56,87.
Addthese,weget21+34+56+87:198,ignorefirst1weget98aslocation
4. DigitAnalysis
Thishashingfunctionisadistributiondependent.
Here we make a statistical analysis of digits of the key, and select those digits (of fixed position)
whichoccurquitefrequently.
Thenreverseorshiftsthedigitstogettheaddress.
Forexample,ifthekeyis:9861234.Ifthestatisticalanalysishasrevealedthefactthatthethirdand
fifthpositiondigitsoccurquitefrequently,thenwechoosethedigitsinthesepositionsfromthekey.
Soweget,62.Reversingitweget26astheaddress.
5. LengthDependentMethod
Inthistypeofhashingfunctionweusethelengthofthekeyalongwithsomeportionofthekeyjto
producetheaddress,directly.
Intheindirectmethod,thelengthofthekeyalongwithsomeportionofthekeyisusedtoobtain
intermediatevalue.
6. AlgebraicCoding
Hereanbitkeyvalueisrepresentedasapolynomial.
Thedivisorpolynomialisthenconstructedbasedontheaddressrangerequired.
Themodulardivisionofkeypolynomialbydivisorpolynomial,togettheaddresspolynomial.
Letf(x)=polynomialofnbitkey=a1+a2x+.+anxn1
d(x)=divisorpolynomial=x1+d1+d2x+.+d1x11
thentherequiredaddresspolynomialwillbef(x)modd(x)
7. MultiplicativeHashing
Thismethodisbasedonobtaininganaddressofakey,basedonthemultiplicationvalue.
Ifkisthenonnegativekey,andaconstantc,(0<c<1),computekcmod1,whichisafractionalpartof
kc.
Multiplythisfractionalpartbymandtakeafloorvaluetogettheaddress
1
0<h(k)<m
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Hashing
DarshanInstituteofEngineering&Technology
CollisionResolutionStrategies(SynonymResolution)
Collisionresolutionisthemainprobleminhashing.
Iftheelementtobeinsertedismappedtothesamelocation,whereanelementisalreadyinsertedthen
wehaveacollisionanditmustberesolved.
Thereareseveralstrategiesforcollisionresolution.Themostcommonlyusedare:
1. Separatechainingusedwithopenhashing
2. Openaddressingusedwithclosedhashing
1. Separatechaining
Inthisstrategy,aseparatelistofallelementsmappedtothesamevalueismaintained.
Separatechainingisbasedoncollisionavoidance.
Ifmemoryspaceistight,separatechainingshouldbeavoided.
Additionalmemoryspaceforlinksiswastedinstoringaddressoflinkedelements.
Hashingfunctionshouldensureevendistributionofelementsamongbuckets;otherwisethetiming
behaviorofmostoperationsonhashtablewilldeteriorate.
ListofElements
0
10
50
1
2
12
32
62
3
4
24
5
6
7
8
9
69
ASeparateChainingHashTable
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Hashing
DarshanInstituteofEngineering&Technology
Example:Theintegersgivenbelowaretobeinsertedinahashtablewith5locationsusing
chainingtoresolvecollisions.Constructhashtableandusesimplesthashfunction.1,2,3,4,5,
10,21,22,33,34,15,32,31,48,49,50
Anelementcanbemappedtoalocationinthehashtableusingthemappingfunctionkey%10.
HashTableLocation
0
1
2
3
4
Mappedelement
5,10,15,50
1,21,31
2,22,32
3,33,48
4,34,49
HashTable
10
15
21
31
22
32
33
48
34
49
50
2. OpenAddressing
Separatechainingrequiresadditionalmemoryspaceforpointers.Openaddressinghashingisan
alternatemethodofhandlingcollision.
Inopenaddressing,ifacollisionoccurs,alternatecellsaretrieduntilanemptycellisfound.
a. Linearprobing
b. Quadraticprobing
c. Doublehashing.
a) LinearProbing
In linear probing, whenever there is a collision, cells are searched sequentially (with
wraparound)foranemptycell.
Fig. shows the result of inserting keys {5,18,55,78,35,15} using the hash function (f(key)=
key%10)andlinearprobingstrategy.
0
1
2
Empty
Table
After
5
After
18
Prof.PradyumansinhJadeja(9879461848)
After
55
After
78
After
35
After
15
15
|130702Data&FileStructure
Hashing
DarshanInstituteofEngineering&Technology
3
4
5
6
7
8
9
18
5
55
18
5
55
18
78
5
55
35
18
78
5
55
35
18
78
Linearprobingiseasytoimplementbutitsuffersfrom"primaryclustering"
When many keys are mapped to the same location (clustering), linear probing will not
distributethesekeysevenlyinthehashtable.Thesekeyswillbestoredinneighborhoodof
thelocationwheretheyaremapped.Thiswillleadtoclusteringofkeysaroundthepointof
collision
b) Quadraticprobing
Onewayofreducing"primaryclustering"istousequadraticprobingtoresolvecollision.
Suppose the "key" is mapped to the location j and the cell j is already occupied. In quadratic
probing,thelocationj,(j+1),(j+4),(j+9),...areexaminedtofindthefirstemptycellwherethe
keyistobeinserted.
Thistablereducesprimaryclustering.
Itdoesnotensurethatallcellsinthetablewillbeexaminedtofindanemptycell.Thus,itmay
bepossiblethatkeywillnotbeinsertedevenifthereisanemptycellinthetable.
c) DoubleHashing
Thismethodrequirestwohashingfunctionsf1(key)andf2(key).
Problemofclusteringcaneasilybehandledthroughdoublehashing.
Functionf1(key)isknownasprimaryhashfunction.
In case the address obtained by f1 (key) is already occupied by a key, the function f2 (key) is
evaluated.
The second function f2 (key) is used to compute the increment to be added to the address
obtainedbythefirsthashfunctionf1(key)incaseofcollision.
The search for an empty location is made successively at the addresses f1 (key) + f2(key),
f1(key)+2f2(key),f1(key)+3f2(key),...
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
Files
WhatisFile?
Afileisacollectionofrecordswherearecordconsistsofoneormorefields.Eachcontainsthesame
sequenceoffields.
Eachfieldisnormallyoffixedlength.
Asamplefilewithfourrecordsisshownbelow:
Name
RollNo. Year Marks
AMIT
1000
1
82
KALPESH
1005
2
54
JITENDRA 1009
1
75
RAVI
1010
1
79
Therearefourrecords
Therearefourfields(Name,RollNo.,Year,Marks)
Recordscanbeuniquelyidentifiedonthefield'RollNo.'Therefore,RollNo.isthekeyfield.
Adatabaseisacollectionoffiles.
Commonly,usedfileorganizationsare:
1. Sequentialfiles
2. Relativefiles
3. Directfiles
4. IndexedSequentialfiles
5. Indexfiles
PrimitiveOperationsonaFile:
1. Creation
2. Reading
3. Insertion
4. Deletion
5. Updation
6. Searching
SequentialFiles
Itisthemostcommontypeoffile.Inthistypeoffile:
Afixedformatisusedforrecord.
Allrecordsareofthesamelength.
Positionofeachfieldinrecordandlengthoffieldisfixed.
Recordsarephysicallyorderedonthevalueofoneofthefieldscalledtheorderingfield.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
Files
Name
AMIT
KALPESH
JITENDRA
RAVI
NILESH
Block1
RollNo. Year
1000
1
1005
2
1009
1
1010
1
Block2
1011
2
Marks
82
54
75
79
89
Someblocksofanordered(sequential)fileofstudentsrecordswithRollno.astheorderingfield
Advantagesofsequentialfileoverunorderedfiles:
Readingofrecordsinorderoftheorderingkeyisextremelyefficient.
Finding the next record in order of the ordering key usually, does not require additional block
access.Nextrecordmaybefoundinthesameblock.
Searchingoperationonorderingkeyismustfaster.Binarysearchcanbeutilized.Abinarysearchwill
requirelog2bblockaccesseswherebisthetotalnumberofblocksinthefile.
Disadvantagesofsequentialfile:
Sequentialfiledoesnotgiveanyadvantagewhenthesearchoperationistobecarriedoutonnon
orderingfield.
Insertingarecordisanexpensiveoperation.Insertionofanewrecordrequiresfindingofplaceof
insertion and then all records ahead of it must be moved to create space for the record to be
inserted.Thiscouldbeveryexpensiveforlargefiles.
Deletingarecordisanexpensiveoperation.Deletiontoorequiresmovementofrecords.
Modification of field value of ordering key could be time consuming. Modifying the ordering field
means the record can change its position. This requires deletion of the old record followed by
insertionofthemodifiedrecord.
Hashing(Directfileorganization):
Itisacommontechniqueusedforfastaccessingofrecordsonsecondarystorage.
Recordsofafilearedividedamongbuckets.
Abucketiseitheronediskblockorclusterofcontiguousblocks.
Ahashingfunctionmapsakeyintoabucketnumber.Thebucketsarenumbered0,1,2...b1.
Ahashfunctionfmapseachkeyvalueintooneoftheintegers0throughb1.
Ifxisakey,f(x)isthenumberofbucketthatcontainstherecordwithkeyx.
Theblocksmakingupeachbucketcouldeitherbecontiguousblocksortheycanbechainedtogetherin
alinkedlist.
Translationofbucketnumbertodiskblockaddressisdonewiththehelpofbucketdirectory.Itgivesthe
addressofthefirstblockofthechainedblocksinalinkedlist.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Files
DarshanInstituteofEngineering&Technology
Hashingisquiteefficientinretrievingarecordonhashedkey.Theaveragenumberofblockaccessesfor
retrievingarecord.
1 bucketdirectory
Thustheoperationisbtimesfaster(b=numberofbuckets)thanunorderedfile.
Toinsertarecordwithkeyvaluex,thenewrecordcanaddedtothelastblockinthechainforbucket
f(x).Iftherecorddoesnotfitintotheexistingblock,recordisstoredinanewblockandthisnewblockis
addedattheendofthechainforbucketf(x).
Awelldesignedhashedstructurerequirestwoblockaccessesformostoperations
Bucket0
230
460
480
580
790
850
Bucket1
321
531
651
Bucket2
232
242
270
930
262
470
420
582
510
b1
Bucket
Directory
Hashingwithbucketsofchainedblocks
Indexing
Indexingisusedtospeedupretrievalofrecords.
It is done with the help of a separate sequential file. Each record of in the index file consists of two
fields,akeyfieldandapointerintothemainfile.
Tofindaspecificrecordforthegivenkeyvalue,indexissearchedforthegivenkeyvalue.
Binary search can used to search in index file. After getting the address of record from index file, the
recordinmainfilecaneasilyberetrieved.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Files
DarshanInstituteofEngineering&Technology
Search
Key
MainFile
Pointer
Name
RollNo
Year
Marks
AMIT
1010
70
1012
KALPESH
1016
80
1015
JITENDRA
1000
65
1016
RAVI
1012
78
NILESH
1015
95
1000
1010
Index
File
IndexfileisorderedontheorderingkeyRollNo.eachrecordofindexfilepointstothecorresponding
record.Mainfileisnotsorted.
Advantagesofindexingoversequentialfile:
Sequentialfilecanbesearchedeffectivelyonorderingkey.Whenitisnecessarytosearchforarecord
on the basis of some other attribute than the ordering key field, sequential file representation is
inadequate.
Multipleindexescanbemaintainedforeachtypeoffieldusedforsearching.Thus,indexingprovides
muchbetterflexibility.
Anindexfileusuallyrequireslessstoragespacethanthemainfile.Abinarysearchonsequentialfilewill
requireaccessingofmoreblocks.Thiscanbeexplainedwiththehelpofthefollowingexample.Consider
the example of a sequential file with r = 1024 records of fixed length with record size R = 128 bytes
storedondiskwithblocksizeB=2048bytes.
Numberofblocksrequiredtostorethefile=
Numberofblockaccessesforsearchingarecord=log264=6
Suppose,wewanttoconstructanindexonakeyfieldthatisV=4byteslongandtheblockpointerisP=
4byteslong.
Arecordofanindexfileisoftheform<V;,Pj>anditwillneed8bytesperentry.
TotalNumberofindexentries=1024
Numberofblocksb'requiredtostorethefile=
Numberofblockaccessesforsearchingarecord=log24=2
Withindexing,newrecordscanbeaddedattheendofthemainfile.Itwillnotrequiremovementof
recordsasinthecaseofsequentialfile.Updationofindexfilerequiresfewerblockaccessescompareto
sequentialfile
64
TypesofIndexes:
1. Primaryindexes
2. Clusteringindexes
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
DarshanInstituteofEngineering&Technology
Files
3. Secondaryindexes
PrimaryIndexes(IndexedSequentialFile):
Anindexedsequentialfileischaracterizedby
o Sequentialorganization(orderedonprimarykey)
o Indexedonprimarykey
Anindexedsequentialfileisbothorderedandindexed.
Recordsareorganizedinsequencebasedonakeyfield,knownasprimarykey.
An index to the file is added to support random access. Each record in the index file consists of two
fields:akeyfield,whichisthesameasthekeyfieldinthemainfile.
Numberofrecordsintheindexfileisequaltothenumberofblocksinthemainfile(datafile)andnot
equaltothenumberofrecordsinthemainfile(datafile).
TocreateaprimaryindexontheorderedfileshownintheFig.weusetherollnofieldasprimarykey.
Each entry in the index file has rollno value and a block pointer. The first three index entries are as
follows.
o <101,addressofblock1>
o <201,addressofblock2>
o <351,addressofblock3>
Totalnumberofentriesinindexissameasthenumberofdiskblocksintheordereddatafile.
Abinarysearchontheindexfilerequiresveryfewblockaccesses
RollNo
BlockPointer
101
101
201
200
351
201
350
351
805
905
IndexFile
400
805
904
DataFile
PrimaryIndexonorderingkeyfieldrollnumber
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Files
DarshanInstituteofEngineering&Technology
ClusteringIndexes
If records of a file are ordered on a nonkey field, we can create a different type of index known as
clusteringindex.
Anonkeyfielddoesnothavedistinctvalueforeachrecord.
AClusteringindexisalsoanorderedfilewithtwofields.
Field
Value
100
Math
100
100
Science
105
105
Physics
BlockPointer
106
108
109
IndexFile
105
105
106
106
108
108
109
109
FieldClusteringDataFile
Exampleofclustering indexonrollno
Secondaryindexes(SimpleIndexFile)
Whilethehashed,sequentialandindexedsequentialfilesaresuitableforoperationsbasedonordering
keyorthehashedkey.Abovefileorganizationsarenotsuitableforoperationsinvolvingasearchona
fieldotherthanorderingorhashedkey.
If searching is required on various keys, secondary indexes on these fields must be maintained. A
secondaryindexisanorderedfilewithtwofields.
o Somenonorderingfieldofthedatafile.
o Ablockpointer
Therecouldbeseveralsecondaryindexesforthesamefile.
Onecouldusebinarysearchonindexfileasentriesoftheindexfileareorderedonsecondarykeyfield.
Recordsofthedatafilesarenotorderedonsecondarykeyfield.
Asecondaryindexrequiresmorestoragespaceandlongersearchtimethandoesaprimaryindex.
Asecondaryindexfilehasanentryforeveryrecordwhereasprimaryindexfilehasanentryforevery
blockindatafile.
Thereisasingleprimaryindexfilebutthenumberofsecondaryindexescouldbequiteafew.
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure
Files
DarshanInstituteofEngineering&Technology
Index Block
Field Pointer
IndexingFieldRollNo
17
10
14
13
10
11
15
12
18
13
14
12
19
15
16
17
18
19
11
16
20
20
IndexFile
DataFile
Asecondaryindexonanonorderingkeyfield
Prof.PradyumansinhJadeja(9879461848)
|130702Data&FileStructure