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

Ds Impp

Uploaded by

26dsmuknu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Ds Impp

Uploaded by

26dsmuknu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

.

:, I~I
~'{:•.,;'::..-,:~

What do You mean by hashtng ? . ·


.. ', .,,, 1;f;;,,.,,,

1. Hashing is a technique that is u ed t<;1. -


·• ·,,,

tJ;,lntify a specific object


·:::·:.
,.,,.
"

from a group of similar object ;. , , . · dl""'


2. Hashing is the transformation cf ""'•':·1 triri -., . · characters into a usually
-s horter fixed-length value ordtey iffltr,presents the original string.

ha.s-
3. In hashing, large keys ~e;i!icoft.;9Wt~.~ ·=r nto small keys by using hash

4.
5.
~c!:i::s are the~~~stru cture called
'nle task ofhashingls t.iJitl,tof>ute entries (key/valu~i..r·-, _Jl~if~mly
·,.i·;-· .~ • •❖... w:•:~::O;;.. •"•f.,.,:,~::~:~~---···
across an array; '.~ .
···;,..

, ·:· , ,.-,;" ·. ).t ,,.-:,,-, t,,/'


-=.l{·\.\\~~-. :· ·; ~\tt!~ ~:%=;::.:.. .,/ .../.. ..\.
6. Each eleme¢ 1s ·a1$igritll"'a key (c9nverted·key).,4~Y _g:_ ;_~t key we

: ~~f§~$~:~€!:'.:.::::e:~:
• 4 .to _f#.ig,: :~ e item us1ng{flict. shdltQY'ha$.hed key than to find 1t

9. ~ ~ : : r : ~ ~ P . ~ ~ can be quickly retrieved


usmg hashed key which IS deffffed by Ji' .
Hash Key = Key ValQe., ,.,f ir~umber of Slots in the Table
·::::;::;:::::.- ·

Discuss types of hash functions.


,: , <r:¥R
, / / h ;.,;.-~

Tt1•• Ill buh funption, :


a. Dlmion method :
1. Clloose a number m larger than the nwnbe f ..
number m is usually chosen to be a . . r n o key 1D K. (The
without small divisors, since this fre !ntmle n~~r or a number
,neolliaion.s.) · q n Y mmumzes the number
·I . '!be hash function His defined by .
H(k) = k (mod m.) . o . H(k)
8. Herek (mod m) denotes th r_ · · = k (mod m,) + 1
e remainder when k is divided by m.
Searching and Sort~ng
3-SE (CSIIT-Sem-3)
4. The second formula is used when we want the hash addresses to
r ange from 1 to m rather than from O to m - ~- ·.
Example t Suppose you have_ a hash t?~l~ with 10 8lot a, _an~ you
want to hash the key "42" using the drv1s1on method. Here s the
calculation :
HashValue = Key % TableSize
HashValtte == 42 % 10
HashValue ::: 2
The key "42" is mapped to slot 2 in the h ash table .
b. Midsquare method :
1. The key k is squared.
2. The hash function H is defined by : H(k)
where l is obtained by deleting digits £; · ofk 2 •
3. We emphasize that the same positi · .., be used for all of
the keys. ,..
Example : Let's say you , ve fl. ',." , and you want to h ash
it using the midsquare m : . , f ' , .~·
Step 1 : Square the key: ·w
Square= (12345)"2 =;, '''\<•. 9, .... .r ·
Step 2: Extract a pqti~n ftla 1tite iniddle (e.g., digits 3i,, 4, and 5):

C.

step l : Divide the key into ~qu '. . 'ized parts (e.g., two digits each) :
Parts : 12, 34, 56, 78, 9 <wr .·
Step 2 : Sum these parts together :
,S um =12 + 34 + 56 + 78 + 9 =189
Step 3: Compute the hash value by taking the remainder when
dividing by 10 (size of the hash table):
HashValue = 189 % 10 = 9
Thus, the key "123456789" is mapped to slot 9 in the hash table.
. Wb~t is h_a•hi:ng ? Give the characteristics of hash
fuaet1on. El<plmn collision reaolution technique in h&11hing. .

@~;~l!~y,.~,i
t;llit;Jm
OR
Data Structure S-9 E (CMT-Sem-3)

What is Hashing ? Explain divlaion method to compute the h~b


function and also explain the colli•ion reaolution •trategie• used m
hashing.

Hashing: Refer Q. 3.8, Pap 3-7E, Unit-3.


Characteriadoe of hMh function :
1. The hash value ia tu.lly determined by the data being hashed.
2. The hash function uses all the input data. .··
3. 'Ihe hash function "uniformly" distributes the ~~ .
·s et of possible hash values. .. . ·
4. The hash function generates very differe~ ·
striilp.
"-•~ . :
•: w~:~~
'IJUU&SIOD
1. Collision is a situation which occur.whe .
key k t.o our file F, but the memo •"'
2. A collision occurs when more t . k ·•· i&ap to same-hash value in
the bash table.
Collisien resolution techJii ... "'"" •
Hashing with open addre · .· ·• .: ·- _,.,f;Y'f:c.

3.
4.
5.

c. · . · , shing
Hashing witli separate chai . .,,,,,,
1. This method maintains the c·ain of ~timents which have same hash
address. ·+:c ,.dfY
2. We can take the hash table as an lt~ay of pointers
3. Size of hash table can be nun1ber of records. ·
4. Here each pointer will poi~t to one_ linked list and the elements which
have same hash address will be n1 aintained in the 11. k .d 1. t
5 w ·t · h .
. . e can_mau\a1n t ~ 1inked list in sortecl order and ea h
n e 1s
.
~ hst_w1H contain the whole record with key. . 1 n

c e e1nents o1
6. For inserting one element, first we have to get th h --
hash function which will map in the hash tabl t~ ashh value through
be inserted in the linked list. e, en t at element will
7. Searching a key is also same, fir 8 t we will get the ha .
. J !lb~e .through hash function, then we will sh key value 1n hash
corresponding linked list. search the element in
( Qui k
\1 c~
,~t.R~ sorts
~l'-~
~)-T ~~·; rm
~L an array
A~,. R,r~i,~_.11 '
~ - " ~ nts.

2: ;/u~ H'l\1 kdflf ~ues ofA onto stack w~ ~


has more elemen ts]
N > 1, tl\fti : TOP TOP + 1, LO~B .tLlJ ·-,:frJ~.J,JPPER [11 N
i}l f := :=

! '!:~7 ::~i!:]TO~U~, y 8
Sef/.13EG,w~y·LoWE R [TOPJ,if!ll ~~!Q:1rl;ril i r -f{TOP],
TOP = TOP - 1 '\i:f@ff,j}Jt,JF*
o;;:,*:-·94,.,,...•
1
h t \ T """--
'····,.·~½:,l,it\.J~{" l"\C"n-)
v l'
~~\

5. Call Quick (A, N, BEG, END; rµ )C) -i"~-,fri_..- _ _ _ __


6. [PUSH left sublist onto stack w~ft has 2 or more elemen ts]
If BEG< LOC - 1 then :
·r op :=TOP + 1, LOWE R [TOP] := BEG,
UPPER [TOP) = LOC - 1
[End of ifstructu re] •
7. [PUSH ·right sublist onto stack when it has 2 or more elemen ts]
lf.LOC + 1 < END, then :
TOP := TOP + 1, LOWE R [TOP] := LOO + 1
UPPER [TOP] := END
[END of if structu re]
[END of step 3 loop]
8. Exit
Anaiy•ia of quick •ort :
Comple xity of worst case is O(n2 ).
'o~ Ol~\ ~\J\\
~ a . a lY\.\~~'I\)
Describe merge sort method. Esplain the complexities
of merse aort method.

Merp aon = (~ s.oist l


a Merge sort is a sorting algorithm that uses the · ,. o :i jjjJ~and conquer.
b. This algorithm divides the array into two . , · v ri.J{hem separately ·
and then merges them. . f .. ·· ,,,,
..~::::-, •, ❖ ·:::,:,:

c. 'nus procedure is recursive_ wi h tli. . ,., e c t a that the number of


elements in the array is not m~ Wk, :': wan·=: {,.,,. .
MERGE_SORT (o-p, r): .,,.,,
l. if, < r +;;me~::;!.> ,❖

l, / A Ip+ i- l]
endfor
5. forj=lton 2
.d0

Rl,1 =A[q + j]
end(or
6. =
~[n1 +. 1) oo, R[n2 ·+ 1] =oo
7. i = 1,J = 1
8. for k = p to r
do
if L[i] sR(/1
then Ark] ~ L[i]
i=i+l
else Ark]= RUJ
i=J + 1
endif
e'6~
g ~lt e')(,t
u.'t)l;S,\j ~ ~ Ol{\ "--~ ~\
(\-\\~. 01}.,e. ~ a l~~l\\
EX'bcfCl m~~~~Ol'n)
~"~ ~~~
MAi \-\tA~1~ tA :\YJ 3-29 1
Data Stru~ture •
t.. t "- \@y\:; t,1
2. r ~ right [i]
3. if l < heap-size IA.] and A [l] > A [i]
4. then largest +- l
5. else largest +- i
6.. if r < heap-size [A] and A [r] > A [larg,est]
7. then largest +- r
8. if largest -:;; i
9. then exchange A[i] ~ A[largest),

10. MAX-HEAPIFY [A, largest]


HEAP-SORT(A) :
1. BUILD-MAX-HEAP (A)
2. for i +- length [A] down to 2 fi

~ '~JJ~ ~
3.
4.
do exchangeA(l] +.+A[i]
heap-size (A] ~ h~
,ti~--
❖%.
e , .~~
-~
~~~$'?

5
··
? '>:tft'fc?!•<<i·•"'f•XW
~-HEAP~ (A, 1)
~ ~'f\\9•~ ~ ~
~~
.Rot.~~'ln) 1

~
t.;.;~%
;:,:;;;,~
!~
11~~'. Write a sl£rit:~ ~-~ .. - ~! - · .
--- ~ ~t~
ct°\ (l'(\ iQ ~~ ~ ® ~ ~\ \~ <;~"~~'2.)
t.. en~ c::,£ ~\ ) 3 ~<.\~1

~, '. ,,,. . . .

t1tr.<:'':/ '. .
1. A 4':- ~ ___________ _ _en, . -
'2· R)ts E'Ctt\ \Je~"' '1-€\J ltn1.
---
~ MA~'t-~tTl~ ) . _ _ __
~·~'at~ ~~~$., Ctt tn~~t~\(\ ~~
b~~~~-w ·
..0.
L\. Ri~ ffict\ ~elC\\\lJt~ n-·\..n
------

- - ---...-¥txi~c~~~ e,~,
~ \~ fl)_\t)-&'tX~t )i- ~ :.L~ ~£-1 \)))
\. 'l. ~ \\ \N he - ~ \n~\e- 9,C)~ce l l.n ~
--·
(), <;~<\) 6 ' (\ ~ \l ~ C n )
Dat a Str uct ure 4-9 E (CSIIT-Sem-3)

Qu e 4.8. )
ey in Bin ary Sea rch
i. Wr ite an iter ative fun ctio n to sea rch a k
Tree <BST>. _:i otir: ,/. , ,~iro,
e sui tab le exa mp le.
ii. Di8CU88 dis adv ant ages of rec urs ion wit h 90m
An swe r )
, PAR)
i. FIN D(I NFO, LEF .r, RIGHT, ROOT, ITE M, LOC i atio n is given.
rch tree Tis the mem ory and d.l11TEM of
A bin ary sea
in T . · the location
This pro ced ure find s the loca tion LOC of ITE M
ci
PA Rof the par ent of ITEM. The re are thre e spe e is emp ty.
1. LOC = NU LL and PAR = NU LL will ind
icat
is the roo t of T.
2. LOC * NU LL and PAR = NU LL will indi c Mi s not in T and
3. LOC = NU LL and PA R* NU LL will ind.
···
•· N cati on PA R:
can be add ed to T as a chil d of
a. [Tre e emp ty ?]
If RO OT = NULL, then : S
Lan d PAR := NU LL, and
Ret urn .
b. [ITE M at roo t ?]
If ITE M = INF O[R : Set LOC := RO OT a,f&,,.p AR := ,.{:;::~ .

NU LL, and Ret ,·. , ..


c. [Ini tiali ze pointt SAVE.]
IfIT EM < ,, O[· en: · 1;1tr:,,
Set PT and SAV E:=

HT[ROOT] and SAVE


stru ctur e.]
ste1.s 5 and 6 while PTR
A a ?] . . .
,,, = INFO[PTR]
and Ret urn .
f. IflT EM < INF O[P rR] , t n:
Set SAV E:= Pl'R and PTR :~,lt ·
\r~
Else :
Set SAVE := PTR and PTR := RIG HT[ PTR ] .
[En d of If stru ctur e]
[En d of step 4 loop.)
PAR := SAVE.
g.
~;:, "ch tlllBuccessful.] Set LOC := NU LL anq
h.
ii. Dia adv ant a,ea of recur11ion :
1. Recursive func tion s · .
s:. ·
t wn. · are gen eral ly s low er tha n non-rec ursi ve
1unc
2· It may requ ire· a lot, of mem ory space to hold inte rme diat e r~su lts
on the 8 .. t ~b.
~~
.
3. Har d to anal yze or underst and the code.
4--14' E (CS/I.T -Sem-3). Trees
. .

/y:
Tree: Refer Q. 4.1, Page 4-2E, Unit-4.
Binary tree :
1. A binary is a non-lin ear data structu re with a maximu m of two children
for each parent.
2. Every node in a binary tree has a left and right referenc e along with the
data element .
3. The node of the top of the hierarc hy of a tree is called the root node.
Comple te binary tree: Refer Q. 4.7, Page 4-8E, Unit"".
Full binary tree :
1. A full binary tree is formed when each missing p,j,r . t',i

replaced with a node ha~ no children . i '<


e,rl'
2. These leaf nodes are drawn as squares · !~e~~; •~'0.1.
h.. })··
;'""''..,_,_ ,,,"'
1 ~

' ' '


Full binary tree.
f'ig. 5.10_.l._
~"...~ i ,:\,·
3. leaf or has degree exac y
· ,,!
~
rder. .
tr•vers al :
or FT, RIGHT, ROOT)
1. "tially ~"'h N1JLL orito STACK, arid.
,,t TOP = : , SiACK [1] = NlJJ:tL an
2. ~
f'tO 5 W
hile ~P'T'R_ ' ,l'Xilo. TT T
~.,..'':/:. Pl U
3. Ap e~ to INFO [Pr .,
4. £Right child?)
If RIGHT [PTR) * NULL
Then
lPush on STACK)
Set TOP= TOP+ 1 and
STACK [TOP) = RIGHT [PfR]
Endif
5. u:.efi child?]
If LEFI' [Pl'R] * NULL then
set PTR = LEFT[P fR]
E~

'tEMif
[Pop from STACK] .
P'ffl = STACK[TOPJ and TOP= TOP- 1
4-18 E (C8/rr .,
Data Structure --------- - - -- ~
--
End of step 2
6. Exit ereal s
Algorithm tor tnorder ' ;;;' ROOT) : ..
Inot-det (JNF'O, LEf"T, IUO OK' and initialize PTRJ
1. [Push NULL o-nto STA NULL and PTR :: ROOT
&t TOP .., 1, STACK l l] "'
. hi1 PTR· .,, NULL TACK]
2. ~P:'At w: e
[Push left.most path onto S d
a. Set TOP = TOP+ 1 an
STACK (TOP] = PTR
b. Set PTR = LEFT [PTRJ
End loop . d TOP= TOP -
3. Set PTR = STACK[TO ~] ~:#:NU LL
4_ Repeat steps 5 to 7 whi~]
Apply process to INFOtc .L n
!: [Right Child?] If RIGHT [Pl'R]
·
Then
a. Set PTR = RIGHT £Pffl
b. goto step 2
Endif
7. Set PI'R = STACK[
End ofStep 4 Loop ·
8. Exit
Algorith m o r traversa l:
Pos · , RIGHT, ROOT)
1. :ACK and initialize PT ·•·
TACK[l] = NULL and Pr
2. th onto STAC!{l
5 while .+f~ U
3. OP+ land ST
[Pushes Ron STACK]
4. HRIGHT [Pl'RJ ~NULL
Then
Set TOP =TOP + 1 and STACK [TOP] =RIGHT [Pl'R]
Endif
5. Set PTR = LEFT [PrRJ
End ,o f step 2 loop
6. Set PrR = STACK {TOP) and TOP :::. TOP - 1
[Pops node from STACK]
7. Repeat while PTR > O
a. Apply process to INFO [Pl'R]
b. Set PTR = STACK [TOP] and TOP = TOP- l
End loop ··
8. If P1'R < 0 Then
a. Set PTR ;:: - PTR
b. 9°-\() \\Q~'l
EN~
<3 -· E~it
Stacks and Queues
2-10 E (CSIIT-Sem-S>
th
6. Function call : Stack is used to keep information about e active
functions or subroutines.
Write an algorithm tot- t,0nverting infts: expression into
postfix expression. Trace your algorithm for infix expression•Q into
its equivalent postfix expression P, Q: A + (B C -
· t · ·. '~ ~f()
(DI IJ"F) • G) • H. ~~ -,,,.,·., .. · ,· ..,,.· ,J';,

Algorithm to convert infix expression to postfix e ·


Step 1 : It the scanned character is an operand. Put i · · .. expression.
Step 2 : If the scanned character is an operator ackisempty
push operation into operator stack.
Step 3 : If the operation stack is not empty the~~ ·owing possibilities.
It the precedence of scanned operator is ,....,.,,~.. " e top most operator
of operator's stack push this operat, · .· tack.
If the scanned character is opening r r ['('], Push it into operator

:=·scanned charact.er is clos · .~ Ji ~ op out operator from operators


stack until we find an openi ket$fl . . · . -~
Step 4 : Now pop out all , , · . ~ g operators from the op · ··" tack
and post into postfix ex . I"
Step 5 : Exit · *
Infix expressio . fii,
n of the form " w
when an . every pair of o
~os pression of the
1s ds is followed
p,
P, * ..

+ +
( +( A
B +( AB
* +(* AB
C +(* ABC
+(- ABC*
( +(-( ABC*
D +(-(
ABc•n
I + (- ( /
ABC*D
E + (- ( /
ABC*DE
Data Structure
2-11 E (CS/IT-Sem-3)

" +( -:--( /" ABC*DE


F +( - ( / " ABC*DEF
)
+(- ABC*DEF"/
* +(- * ABC*DEF"/
G +( - * ABC*DEF"/0
) + ABC*DEF"/0 * -
* +* ABC*DEF"/0 * -
H +* ABC*DEF"/0 * -H
ABC*DE.

Postfix expression ABC * DEF " I G * -

Write algorithm for push an


Transform the following expressio
expression using stack : ·.
A + (B * C - (DIE t F) * q

~~~~~~ttiit;;:il
Algorithm for push
Page 2-3E, Unit-2.

/ A
A
AB
AB
ABC
ABC*
ABC*
(
D
! (-:,,~
~~f-J,,, ABC*D
+ ~;~ ( / ABC*D
I
E + (- (/ ABC*DE
t +< - ut ABC*DE
F + (- (It ABC*DEF
) + (- (It ABC*DEF
* + (- * ABC*DEF t/
G + (- * ABC*DEF t/ G
) + ABC*DEFt/G* -
* +* ABC*DEFt/G* -
H +* ABC*DEFt/G* - H
ABC*DEFt /G* - H*+
-'·Jlesultant postfix expression : ABC*DEFt/G* - H* +
Dat a Stru ctu re
2-I o E (CS/IT-Sem-3)

t =(+t
112 =(+t 112
)
I
= t+
=I
( =I(
2 =I( 2
X =l (x
a =l (x a
) =I X

En d of exp res sio n

1. n of a process in
of outcomes.
,,$al
¥v ue.
2. ppr oac h so~.~ en tfi'
epr oc , and the resu lt of each
3.
est · iter atio n.
iter a
Iter atio n allows us to sim ph , ithm by stat ing tha t ~e will
4.
rep eat cert ain step s unti l told.
sim pler because they do
5. Thi s mak es des igni ng algo rith ms icke r and
s.
not hav e to include lots of unn ece ssar y step
eat a set of inst ruct ions .
6. Iter atio n is use d in com pute r pro gram s to rep
stru ctio ns upto a specific
7. Cou nt controlled iter atio n will repe at a set ofin
iter atio n will rep eat the
num ber of times; while condition controlled
inst ruct ions unti l a specific condition is met.
What is rec urs ion ? Exp lain .

tha t call s itse lfto perform


1. Recursion is a process of expressing a function
specific operation.
Stacks and Queues

Indirect recursion occurs when one function calls another function that
2.
then calls the first function.
Suppose pis a procedure containing either a call statement to itself or
3. a call statement to a second procedure that may eventually result in a
call statement back to the original procedure P.
Then Pis called recursive procedure. So the program will not continue
4.
to run indefinitely.
5. A recursive procedure must have the following two properties :
a There must be certain criteria, called base criteria, for which the
procedure does not call itself. •. ·
b. Each time the procedure does call itself; · · oser to the
criteria.
A recursive procedure with these two '.
defined. ,
"~·
7. Similarly, a function is said t tfi>e lei~ si . defined if the function
definition refers to itself.

Write a recurs~ 'J)l'Ogl"am to find sum of digits of the


given number. Also, calcula~ t~ e time complexity.

Program:
t~Y

else
return(n % 10 + sum (n / lO~J' .

main()
{

int s,n;
printf(" \nEnter any number-")·
8Canit"%d"& )· . '
' n'
s = sum(n);
printf("\nSum of d'1gits
· - %d"
getchO; - , s );
Data Structure 2-11 E (CS/IT-Sem-3)
return 0;
}
Time complexity :
1. Assume t~at n is a 10 digit number. The function is called 10 times as the
problem 1s reduced by a factor of 10 each time the program recurse.
ll. So, we can conclude that time taken by program is linear in terms of th
length of the digit of the input number n. e
ill. So, time ,complexity is,
~n_) ~ O(le~h of digit of (n)) where n is the numl5er whose sum of
mdividual digit is to be found. '
'"'r7
Explain all types of recursion
' '
'
~~\~

Types of recursion :
a. Direct recursion : A functio
explicit call to itself.
For example :
int foo (int x)
{ if(x <= 0)
returnx;
return foo (x -
}
b. I unction is indirec
C n.

returnx;
return bar (x) ;
}
int bar (int y)
{ return foo (y - 1) ;
}
e. Tail recursion :
1. Tail recursion (or tail-end recursion) is a special case ofrecursion in
which the last operatiop of the function, the tail call is a recursive
call. Such recursions can be easily transformed to iterations.
2. Replacing recursion with iteration, manually or automatically, can
drastically decrease the amount of stack space used and improve
efficiency.
3. Converting a call to a branch or jump in such a case is called a tail
call optimization. ·
2-18 E (CSIIT-S em-3) Stacks and Queues

For es.ample :
Consider this recursive definition of the factorial function in C :
factorial (n)
{
if( n == 0)
return 1;
return n • factorial (n - 1);
}
4. This definition is tail recursive since the recursive call to factorial is
not the last thing in the function (its result has to be multiplie d by
n).
factorial (n, accumula tor)
{
if(n == 0)
return accumula tor;
return factorial (n - 1, n * a'cc>fllulator );
}
factorial (n) ··
(
return factorial. (' - 1) ;

cl Linear and tree recursiv e :


1. A recursive ~ction is said to be linearly recursive vpien np pending
oneratjo
"'- ,, ~ involve& another recursive call to the function.
2., ~
«~~A.$; , ,, · ction is said to be tree recursive l_r non-linea rly
J recu ~~e)
~ ~ ,,
en the pending operafio n does involve another
I~ recurslfe call to the function.
• nacci function 1ih provid~ a .classic example of tree
, n. The Fibonacc i numbers can ~ defined by the rule :
int fit (int n)
{ /* n >= 0 */
if (n == 0)
returnO;
if (n == 1)
return 1;
return fib (n - 1) + fib (n - 2) ·
} '

Th~ pending ope~ation for the recursive call is another call to fib. Therefor e,
fib 18 tree recursive .

,: ···,,: Differen tiate between iteratio n and recursio n.

( AKTU 2019-to, Marks 10]


pata Stru ctur e

----- 2-19 E (CS/IT-Sem-3)

1. Allows the set of inst ruct ions to


be repe ated ly exec uted . The stat eme nt in a body of
func tion call s the func tion
itself.
2. It.eration incl udes initi aliza tion ,
con diti on, exe cuti on of In recu rsiv e func tion , only
stat eme nt with in loop and term inat ion cond ition (bas e
case ) is spe ·
upd ate the cont rol vari able .
3. It.eration cons ume s less memory.

4. Infi nite loop uses CPU cycl es


repe ated ly.
5. Iter atio n is appl ied to c sion is alwa ys appl ied to
iter atio n stat eme nts or , , ctio ns.
6.
7. Fas t in exec uti ,,
8.

i.
ii. m to calc
n-re cur ·

Def ine the recu rsio n. Wri te a re d non -rec ursi ve pro gram
to calc ulat e the fact oria l of the gil ·

i. Rec urs ion: Refe r Q. 2.15, Pag e 2-15 E, Unit -2.


ii. Pro gra m :
#include <stdio.h>
#include <conio.h>
void main()
{
int n, a, b;
clrscr();
prin tf("E nter any num ber\ n");
scanf("%d", &n);
2-20 E (qS/IT-Sem-S) Stacks and Queues

a= recfactorial(n): . ber using recursion is %d


printfl"The factorial of a g1von num
\n", a);
b = nonrecfactorial(n); . _ . • nrocursio:n is %d ", b);
printfl"The factorial of a given number using no
getch(}; .
}
int recfactorial(int x)
{
intf;
iflx == 0)
{
return(l}.;
}
else
{
f = x * recfactorial(x - 1);
,
return(f);

}
int nonrecfactorial(int x
{
inti, f = 1;
for(i = 1; i <= x; · +
{

1. Suppose three pegs, labelled A, - is given, and suppose on peg A,


there are finite number of n disks ith decreasing size.
2. The object of the game is to move·the disks from peg A to peg C using
peg B as an a~liary.
3. The rule of game is follows :
a. Only one disk may be moved at a time. Specifically only the top disk
on any peg may be moved to any other peg.
A B C
Df\ta Structµre
2-21 E (CS~T-Sem-3)
b. At no time, can a larger disk be 1
The solution to the Tower of H~oi : a~i.d o~. a smaller disk.
Ai I /4 i•or,o1·11
Initial (l)A ➔ C ( 2 ) A ➔ :B
1

,11 l i LA.lnLc1
(3) C ➔ B
A B C
(4) A ➔ C
A
·· 5Y,1J ➔ A
,,

I
l Ik ~

'fotal num,ber Qf steps to sol anoi problem of n disk


= 2n =7

Writether

char = 'A', B = 'B', C


void b.anoi (int, char, char, c ar ·
printf("Enter number of qislt'.
scanft"%d", &n); . . "
printf("\n \n Tower of Hanoi problem with %d disks \ n , n);
printf<"Sequence is: \n");
hanoi (n, A, B, C);
printtt(' \ o"');
get,eh();

..:i::!f',qid ~oi (int n, char A, char B, char C)


.. ' ." ' {
· ··fflu ! = O)
{ ' ,,

}Wloi (n - 1, A, C, B);
r'

Data Structure 2-3 E (CSIIT-Sem-3)

v. Overflow : To check whether the 8tack. is full.


vt. Underflew : To check whether the 8tack is empty.
Write short not,e on abAt ract data type.

Refer Q. 1.11, Page 1- 9E, Unit-1.


Diacu.ss PUSH and POP operation in &tack and write
down their alprithm.

PUSH o.peration : In push operation, we inser · t onto stack.


Before inserting, first we increase ~e top pointe rt the element.
Algorithm :
PUSH(STACK, TOP, MAX, DATA) .·
1. If TOP= MAX- 1 then write "Si
2. READDATA /.

3. TOP-+-TOP + 1
4. STACK [TOP] +- DATA
5. S'IOP
POP operation: In pop remove an element from
every pop operation top o ecremented by -1. ·
Algorit hm:
POP (STACK, T .
1. IfT CKUNDERFL
2. S
3.
4.

Write a C function for array implementatio n of st.a ck.


Write all primitive operation•.

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

I #define MAX 50
int stack [MAX + 1], top = 0 ;
voidmain()
{
clrscr( );

You might also like