You are on page 1of 171

# Department of CSE and IT, JUIT Waknaghat

Practical No.1
_______________________________________________________________________ _ I!" Getting acquainted with recursion.

#\$JECTI%E
The goal of this lab is to help you become acquainted with the use of recursion. Recursion is an ability of a function to call itself. In c it is possible for the function to call themselves. A function is called recursive if a statement with in the body of a function calls the same function.

E& !P'ES" Re cu r s io n :s u m ()

Re cursion: sum()

## " Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat E(ample" factorial) # # *+ , * - . - / - 0 - 1 \$otice that *+ , * - .+ .+ , . - /+ ... %an compute factorials recursively &olve base case '1+ , 1+ , 1( then plug in 0+ , 0 - 1+ , 0 - 1 , 02 /+ , / - 0+ , / - 0 , 32

# #

Re cursion

4-Program for calc5lating the factorial of a n5m6er 67 5)ing rec5r)i8e f5nction-4 )include*stdio.h+ )include*conio.h+ int rec 'int(, void main'( int a. fact, printf'/enter any no0(, scanf'/1d0.2a(, fact3rec'a(, printf'/1d0. fact(, 4 rec9int (: ; 5 Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat int f2 if9(,,1: ret5rn91:2 el)e f,(-rec9(<1:2 ret5rn9f:2 = >ec5r)ion %). Iteration" Repetition # Iteration6 e7plicit loop # Recursion6 repeated function calls Termination # Iteration6 loop condition fails # Recursion6 base case recogni8ed 9alance # %hoice between performance 'iteration( and good software engineering 'recursion( #

STUDENT T S?S"
1. Write a recursive function to obtain the first 25 numbers of a Fibonacci series. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence: 1 2 3 5 8 13 21 . 2. Write a recursive function to obtain the running sum of first 25 natural numbers. 3. ! "ositive integer is entered through the #e\$board% write a recursive function to obtain the "rime factors of that integer. &. Write a "rogram to calculate result of following with recursive calls of a function. '(2)&)*)8..n '(1+1,)2+2,)3+3,) n+n,. 5. ! five digit "ositive integer is entered through the #e\$board% write a recursive function to calculate the sum of digits of 5 digit number. *. Write a recursive function to find out the -./ of numbers. 0. Write a recursive function to generate table of a number.

## Department of CSE and IT, JUIT Waknaghat

Practical No.0
_______________________________________________________________________ _ I!" Getting acquainted with recursion with pointer.

#\$JECTI%E
The goal of this lab is to help you become acquainted with the use of recursion with pointers. Recursion is an ability of a function to call itself. In c it is possible for the function to call themselves. A function is called recursive if a statement with in the body of a function calls the same function.

STUDENT T S?S"
1. Write a recursive function to find out the reverse of a string using "ointers. 1g. \$ashwant o+"% tnawhsa\$ 2. Write a recursive function to determine whether a string is "alindrome2 .a"itali3ation and s"acing are ignored. 4est \$our with the following two "alindromes and at least one case that is not a "alindrome. 5adam2 I6m !dam !ble was I ere I saw 1lba 3. Write a recursive function that convert a string of numerals to an integer. For e7am"le2 8&35*09 will be converted to &35*0. &. Write a recursive function that changes an integer to a binar\$ number. 5. Write a recursive function that removes all the occurrences of a s"ecified character in a string.

## Department of CSE and IT, JUIT Waknaghat

Practical No./
_______________________________________________________________________ _

I!" Revision of arrays. strings. pointers. recursion and dynamic memory allocation. #\$JECTI%E
The goal of this lab is to help you become acquainted with the use of arrays. strings. pointers. recursion and dynamic memory allocation.

STUDENT T S?S"
1. ! m 7 n matri7 is said to have a saddle "oint if some entr\$ a:i;:<; is the smallest value in row i and the largest value in column <. Write a . "rogram that determines a saddle "oint if one e7ists. 2. ! square matri7 ! of si3e m 7 n is said to be s\$mmetric if element a i< ( a<i2 for all values of I and <. Write a function sa\$2 int is=\$mmetric>int a:;:;2 int n? that returns value 1 if the in"ut matri7 is s\$mmetric else return value @. 3. Write a function that removes leading s"aces from a given string. &. Write a function that concatenates first n characters of a string to another string. 5. Write a recursive function to find out whether a string is "alindrome or not.

## Department of CSE and IT, JUIT Waknaghat _______________________________________________________________________ _

Practical No..
_______________________________________________________________________ _ I!" Getting acquainted with =in>ed list ' =inear =in>ed =ist(.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to create lin>ed list. insert elements into lin>ed list. traverse the lin>ed list. delete elements from the lin>ed list.

'i)t"
=ist is homogeneous collection of elements. with linear relationship between the elements. the list can be ordered or unordered. ? Implementing li)t =ist can be implemented using !. =inear array ". =in>ed list ?

## rra7 Implementation of 'i)t"

The linear array can be created at the compilation time by using type declaration statement of type int a@!AAB, ? Chich create linear array with !AA elements ? &ince each elements ta>es two bytes of memory. the compiler allocates "AA bytes for the array. ? The above array can be created at run time with the following declaration statement int Da, a3'intD(malloc'!AADsi8eof'int((, In the above declaration. the malloc'( function allocates "AA bytes of memory and assign the address of the first byte to the pointer variable a. 'imitation) of an arra7 ? Insertion and deletion operations are e7pensive. ? Inserting at first position requires first pushing the entire array down by one position to ma>e room. ? Eeleting the first element requires shifting all the elements in the list one position up. ? &o worst case of these operation is F'n(. ? &i8e of the list must be >nown in advance. 'inked implementation of li)t ? To avoid the linear cost of insertion and deletion operations. we need to ensure that the elements of the list are not stored contiguously. ? =in>ed list basically consists of series of structures. which are not necessarily adGacent in memory H Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi ?

Department of CSE and IT, JUIT Waknaghat Iach structure contains an element of the list and a pointer to structure containing its successor. ? =in>ed implementation allow traverse and search operations to be carried out in linear time. ? Insertion and deletion operations can be implemented efficiently as it requires only rearrangement of pointers. 'inked li)t defined A lin>ed list is a linear collection of data elements. called nodes. the linear order is given by pointers. Iach node is divided into two or more parts. =in>ed list can be of following types6 ? =inear lin>ed list or one way list ? Eoubly lin>ed list or two way list ? %ircular lin>ed list ? Jeader lin>ed list ?

In a linear linked list, also called singly linked list or one way linked list, each node is divided into two parts. First parts contain the information of the element Second part called the linked field or next pointer field, contains the address of the next node in the list.
head 1200 1201 1202 120 !

"ext pointer field of 2nd node Information field of second node head is #sed to hold the address of first element of the list. \$ast element of the linked list have "%\$\$ val#e in the next pointer field to mark the end of the list

>epre)entation of 'inear linked li)t &uppose we want to store the list of integer numbers. then the linear lin>ed list can be represented in memory with the following declarations. t7pedef )tr5ct nodet7pe ; int info2 )tr5ct nodet7pe -ne(t2 =node2 node -head2 The above declaration define a new data type. whose each element is of type nodetype and gives it a name node. #peration on 'inear linked li)t) ? %reating an empty list ? Traversing a list ? &earching an element ? Inserting an element ? Eeleting an element Creating an empt7 li)t K Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

STUDENT T S?S"
1. W!A to im"lement the Binear lin#ed list. Aerform the following o"erations on the lin#ed list: !ddition of numbers after a "articular location. /eletion of the number given b\$ the user. .ounting the no of nodes. /is"la\$ing the lin#ed list. !5 Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat !dding the numbers at the beginning of the lin#ed list. !""ending the numbers given b\$ the users.

## 2.W!A for reversing the lin#ed list.

Practical No.*
_______________________________________________________________________ _ I!" Getting acquainted with =in>ed list ' =inear =in>ed =ist(.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to create lin>ed list. insert elements into lin>ed list. traverse the lin>ed list. delete elements from the lin>ed list.

STUDENT T S?S"
1. 4wo lin#ed lists are given as !: 12 22 32 &2 52 * C: 02 82 D2 1@2 112 12 5a#e a third lin#ed list so that it is in the following order. .: 12022282 ..2*212 2. W!A for "rinting the common elements in two given lin#ed lists. 3. W!A that traverse a list im"lemented using lin#ed list and delete all nodes whose #e\$s are negative. &. ! lin#ed list contains some "ositive numbers and some negative numbers. Ese this lin#ed list to W!A for creating two more lin#ed list2 one containing all "ositive no and other all negative nos.

## Department of CSE and IT, JUIT Waknaghat

Practical No.3
_______________________________________________________________________ _ I!" Getting acquainted with =in>ed list 'Eoubly =in>ed =ist(.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to create doubly lin>ed list. insert elements into lin>ed list. traverse the lin>ed list. delete elements from the lin>ed list. Do56l7 'inked 'i)t In doubly lin>ed list. also called the two way list. each node is divided into three parts6 ? The first part called. previous pointer field. contains the address of preceding element in the list. ? The second part contains the information of the list. ? The third part. called ne7t pointer field. contains the address of the succeeding element in the list. In addition. two pointer variables. e.g. head and tail. are used that contains the address of first element and the address of last element of the list.

## head ! 1200 1201 120 !

tail

"ext pointer field of 2nd node Information field of second node &revio#s pointer field of 2nd node

>epre)entation of do56l7 linked li)t ? &uppose we want to store list of integer. t7pedef )tr5ct nodet7pe ; )tr5ct nodet7pe -pre82 int info2 !; Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat Dtail3ptr, 4 else ptrP+prev3loc, ptrP+ne7t3locP+ne7t, 'locP+ne7t(P+prev3ptr, locP+ne7t3ptr, 4 4 In)erting 6efore a gi8en element" Loid insertbeforeelement 'node DDhead. node DDtail. int item. int before( node Dptr. Dloc, ptr3head, loc3search'ptr.before(, if'loc33\$M==( return, ptr3'nodeD(malloc'si8eof'node((, ptrP+info3item, if'locP+prev33\$M==( ptrP+prev3\$M==, locP+prev3ptr, ptrP+ne7t3Dhead, Dhead3ptr, 4 else ptrP+prev3locP+prev, ptrP+ne7t3loc, 'locP+prev(P+ne7t3ptr, locP+prev3ptr, 4 4 Deleting an element ? To delete an element from the list. first the pointer are set properly and then the memory occupied by the node to be deleted is deallocated 'freed(. ? The deletion in the list can ta>e place at the following positions. !. At the beginning of the list ". At the end of the list 5. After a given element :. 9efore a given element Deleting from the 6eginning of the li)t" An element from the beginning of the lists can be deleted by performing following steps6 ? Assign the value of head ' address of the first element of the list( to a temporary variable 'say ptr( ? Qurther there are two cases6 !. If there is only one element in the e7isting list. both head and tail variable are set to \$M==. !R Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat Loid ideleteafterelement 'node DDhead. node DDtail. int item. int after( node Dptr. Dloc, ptr3head, loc3search'ptr.after(, if'loc33\$M==( return, else if''locP+ne7t(P+ne7t33\$M==( ptr3locP+ne7t, locP+ne7t3\$M==, Dtail3loc, free'ptr(, 4 else ptr3locP+ne7t, locP+ne7t3ptrP+ne7t, 'ptrP+ne7t(P+prev3loc, free'ptr(, 4 4 Deleting 6efore a gi8en element" Loid ideleteafterelement 'node DDhead. node DDtail. int item. int before( node Dptr. Dloc, ptr3head, loc3search'ptr.before(, if'loc33\$M==( return, else if''locP+prev(P+prev33\$M==( ptr3locP+prev, locP+prev3\$M==, Dhead3loc, free'ptr(, 4 else ptr3locP+prev, locP+prev3ptrP+prev, 'ptrP+prev(P+ne7t3loc, free'ptr(, 4 4 The doubly lin>ed list can be deleted either by heading from the beginning or from the end. The list can be deleted from the beginning by performing the following steps6 ? Assign the head pointer to a temporary variable. say ptr. ? Advance the head pointer to the ne7t node. ? Eeallocate the memory occupied by the node pointed to by ptr. "! Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat The above steps are repeated till the entire list is deleted. Qinally the tail pointer is set to \$M== value. Deleting entire li)t Loid deletelist'node DDhead. node DDtail( node Dptr, while'DheadN3\$M==( ptr3Dhead, Dhead3'Dhead(P+ne7t, free'ptr(, 4 Dtail3\$M==, 4

STUDENT T S?S"
1. W!A to im"lement the doubl\$ lin#ed list. Aerform the following o"erations on the lin#ed list: !ddition of a number after a "articular location. !ddition of a number before a "articular location /eletion of a number after a "articular location. /eletion of a number before a "articular location /eletion of the number given b\$ the user. .ounting the no of nodes. /is"la\$ing the lin#ed list from both head and tail.. !dding the numbers at the beginning of the lin#ed list. !dding the numbers at the end of the lin#ed list. 2. -iven a doubl\$ lin#ed list whose elements are of t\$"e integer2 write function that co"ies the even integer numbers in one list and odd integer numbers in another list. 3. Write a recursive function to reverse a doubl\$ lin#ed list.

## Department of CSE and IT, JUIT Waknaghat

Practical No.@
_______________________________________________________________________ _ I!" Getting acquainted with =in>ed list '%ircular =in>ed =ist(.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to create %ircular lin>ed list. insert elements into lin>ed list. traverse the lin>ed list. and delete elements from the lin>ed list. Circ5lar 'inked 'i)t A circular list is a linear lin>ed list. e7cept that the last element points to the first element. Qor non empty circular lin>ed list there are no \$M== pointer. The memory declarations for representing circular lin>ed lists are the same as for linear lin>ed lists Propertie)" ? Can reach entire li)t from an7 node ? Need )pecial te)t for end of li)t ? U)ed a) 65ffer A %ircular =in>ed =ist is a special type of =in>ed =ist It supports traversing from the end of the list to the beginning by ma>ing the last node point bac> to the head of the list. ? %ircular lin>ed lists are usually sorted ? %ircular lin>ed lists are useful for playing video and sound files in /looping0 mode. ? They are also a stepping stone to implementing graphs. an important topic in computer graphics. >epre)entation of Circ5lar linked li)t &uppose we want to store the list of integer numbers. then the circular lin>ed list can be represented in memory with the following declarations. t7pedef )tr5ct nodet7pe ; int info2 )tr5ct nodet7pe -ne(t2 =node2 node -head2 The above declaration define a new data type. whose each element is of type nodetype and gives it a name node. ? ?

## Department of CSE and IT, JUIT Waknaghat

'll operations performed on linear linked list can (e easily extended for circ#lar linked lists with following exceptions) 1. *hile inserting new node at the end of the lists, its next pointer field is made to point to the first node. 2. *hile testing for the end of the lists, we compare the next pointer field with the address of the first node.

1201

12 +

1 +,

## Circular Linked with 3 Nodes

#peration on 'inear linked li)t) ? %reating an empty list ? Traversing a list ? &earching an element ? Inserting an element ? Eeleting an element

STUDENT T S?S"
1. W!A to im"lement the .ircular lin#ed list. Aerform the following o"erations on the lin#ed list: !ddition of numbers after a "articular location. /eletion of the number given b\$ the user. .ounting the no of nodes. /is"la\$ing the lin#ed list. !dding the numbers at the beginning of the lin#ed list. !""ending the numbers given b\$ the users. 2. Write a function that removes all du"licate elements from a linear lin#ed list. 3. Write a function that creates a new circular linear lin#ed list b\$ selecting alternate elements of a given circular linear lin#ed list.

## Department of CSE and IT, JUIT Waknaghat

Practical No.A
_______________________________________________________________________ _ I!" Getting acquainted with &tac>s.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to create stac> '=IQF(. pushing elements into stac>. popping elements from the stac>. chec>ing stac> for overflow and underflow.

Stack)
? ? ? ? &tac> is one of the commonly used data structures. &tac> is also called last in first out '=IQF( system &tac> is a linear list in which insertion and deletion can ta>e place only at one end called top. This structure operates in much the same way as stac> of trays.

Stack of -rays

## "; Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat -he following fig#re ill#strate a stack, which can accommodate maxim#m of 10 elements fig#re shows stack after p#shing elements .,10,12,/,,0

2 . 1 0 , top + 2 1 0 0 /, 12 10 .

## Stack after popping top two elements

2 . 1 0 , + top 2 1 0 12 10 .

## stack after p#shing elements .,10,12,/,,0,2,,,

2 . 1 top 0 , + 2 1 0 ,, 2 0 /, 12 10 .

#peration) on )tack) ? Create)tack9):Bto create s as an empty stac> ? P5)h9),i:<<to push elementi onto stac> s. ? Pop9):Bto access and remove the top element of the stac> s ? Peek9):Bto access the top element of the stac>s without removing it from the stac> s. ? I)f5ll9):Bto chec> whether the stac> s is full ? i)empt7Bto chec> whether the stac> s is empty >epre)entation of )tack in memor7 ? >epre)entation of )tack 5)ing arra7" &uppose elements of the stac> are integer type and stac> can store ma7imum !A elements.. )define TAU !A typedef struct int top, int elements@TAUB, 4stac>, stac> s, ? Jere we have defined our own data type named stac>. ? Qirst element top will be used to inde7 top element ? Array elements hold the elements of the stac> ? =ast line declares variable s of type stac> ? In addition to the previous declaration. we will use the declaration t7pedef en5m ;fal)e, tr5e = \$oolean2 This statement defined new data type named 9oolean which can ta>e value false or true.

## 3epresentation of stack in memory

0 + top 0 2 top 1 2 + , 0 1 . 2 1 2 + , 0 1 . 2

10 12 /,

10 12

0 0 top

10 12 /,

,,

? ? ?

\$efore Ce can 5)e a )tack, it i) to 6e initialiDed. ) the inde( of arra7 element) can take an7 8al5e in the range 1 to ! &<1, the p5rpo)e of initialiDing the )tack i) )er8ed 67 a))igning 8al5e <1 to the top of 8aria6le. Thi) )imple ta)k can 6e accompli)hed 67 the folloCing f5nction.

%oid create)tack9 )tack -p): ; p),<12 = Te)ting )tack for 5nderfloC 9oolean isempty'stac> Dps( if'psP+top33P!( return true, else return false, 4 or 9oolean is empty'stac> Dps( return ''psP+top33P!(Vtrue6false(, 4 Te)ting )tack for o8erfloC 9oolean isfull'stac> Dps( if'psP+top33TAUP!( return true, else return false, "K Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat 4 or 9oolean is empty'stac> Dps( return ''psP+top33TAUP!(Vtrue6false(, 4

Push Operation
4efore the p#sh operation, if the stack is empty, then the val#e of the top will (e /1and if the stack is not empty then the val#e of the top will (e the index of the element c#rrently on the top. -herefore we place the val#e onto the stack, the val#e of top is incremented so that it points to the new top of stack, where incoming element is placed. 5oid p#sh6stack 7ps, int val#e8 9 ps/:top;;< ps/:elements=ps/:top>?val#e< @

Pop Operation
-he element on the top of the stack is assigned to a local varia(le, which later on will (e ret#rned via the ret#rn statement. 'fter assigning the top element to a local varia(le, the varia(le top is decremented so that it points to a new top Int pop6stack 7ps8 9 int temp< temp?ps/:elements=ps/:top>< ps/:top//< ret#rn temp< @

## 'ccessing top element

-here may (e instances where we want to access the top element of the stack witho#t removing it from the stack. Int peek6 stack 7ps8 9 ret#rn6ps/:elements=ps/:top>8< @

## 3epresenting a stack #sing a linked list

' stack represented #sing a linked list is also known as linked stack. -he array (ased representation of stack s#ffers from following limitations. SiAe of the stack m#st (e known in advance *e may come across sit#ation when an attempt to p#sh an element ca#ses overflow. Bowever stack is an a(stract data str#ct#re can not (e f#ll. Bence, a(stractly, it is always possi(le to p#sh an element onto stack. -herefore stack as an array prohi(its the growth of the stack (eyond the finite n#m(er of elements.

## Department of CSE and IT, JUIT Waknaghat

Ceclaration of stack
-he linked list representation allows a stack to grow to a limit of the comp#terDs memory. Typedef struct nodetype { int info; struct nodetype *ne t; !stack; "tack *top; Bere I have defined my own data type named stack, which is a self referential str#ct#re and whose first element info hold the element of the stack and the second element ne t hold the address of the element #nder it in the stack. -he last line declares a pointer varia(le top of type stack.

## 3epresentation of stack in memory

top 0 /, 12 10 . !

top 0 /, 12 !

top ,, 2 0 /, 12 10 . !

## -esting stack for #nderflow

4oolean isempty6stack 7top8 9 if6top??"%\$\$8 ret#rn tr#e< else ret#rn false< @ or 4oolean is empty6stack 7top8 9 ret#rn 66top??"%\$\$8Etr#e)false8< @

## -esting stack for overflow

Since stack represented #sing a linked list can grow to a limit of comp#ters memory, there overflow condition never occ#rs. Bence this operation is not implemented for linked list.

&#sh operation
-o p#sh a new element onto the stack, the element is inserted in the (eginning of the linked list. void p#sh6stack 77top, int val#e8 9 stack 7ptr< ptr?6stack78malloc6siAeof6stack88< if6ptr??"%\$\$8 9 printf6FGn #na(le to allocate memory for new nodeHI8< printf6FGnpress any key to exit..I8< getch68< ret#rn< @ ptr/:info?val#e< ptr/:next?7top< 7top?ptr< @

## 'ccessing top element

Int peek6stack 7top8 9 ret#rn6top/:info8 @

&op operation
-o pop an element from the stack, the element is removed from the (eginning of the linked list. Int pop6stack 77top8 9 int temp< stack 7ptr< temp?67top8/:info< ptr?7top< 7top?67top8/:next< free6ptr8< ret#rn temp< @

## Department of CSE and IT, JUIT Waknaghat

Cispose a stack
4eca#se the stack is implemented #sing linked lists, therefore it is programmers Jo( to write the code to release the memory occ#pied (y the stack. #oid disposestack\$stack **top% { stack *ptr; while\$*top&'N(LL% { ptr'*top; *top'\$*top%)*ne t; free\$ptr%; ! !

STUDENT T S?S"
1. Write a menu driven "rogram to im"lement the various o"erations on a stac# re"resented using an arra\$. 2. Write a menu driven "rogram to im"lement the various o"erations on a stac# re"resented using lin#ed list. Various operations are: ? Createstack(s)to create s as an em"t\$ stac# ? ush(s,i)!!to "ush elementi onto stac# s. ? op(s)to access and remove the to" element of the stac# s ? eek(s)to access the to" element of the stac#s without removing it from the stac# s. ? "s#u\$\$(s)to chec# whether the stac# s is full ? isempt%to chec# whether the stac# s is em"t\$

## Department of CSE and IT, JUIT Waknaghat

Practical No.E
_______________________________________________________________________ _ I!" Getting acquainted with Applications of &tac>s in e7pression evaluation.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to implement infi7. postfi7 and conversion from infi7 to postfi7 notation.

'pplications of Stacks
Stacks are #sed to pass parameters (etween f#nctions. Kn a call to f#nction, parameter and local varia(les are stored on stack. Bigh level programming lang#ages, s#ch as &ascal c etc. that provide s#pport for rec#rsion #se stack for (ook keeping. In each rec#rsive call, there is need to save the c#rrent val#es of parameters, local varia(les and the ret#rn address. In addition to a(ove stack are #sed to solve the vario#s pro(lemsH. 1. &arenthesis checker 2. Lathematical notation translation
1. &olish 6prefix8 notation 2. 3everse polish 6postfix8 "otation

## . M#ick sort algorithm

Parenthesis checker
&arenthesis checker is a program that checks whether a mathematical expression is properly parenthesiAed. *e will consider three sets of gro#ping sym(ols)
N -he standard parenthesis I6 8I N -he (races F9 @I N the (rackets F= >I For an inp#t expression, it verifies that for each left parenthesis, (races or racket, there is a corresponding closing sym(ol and the sym(ols are appropriately nested.

## Oxamples of valid inp#ts

5alid Inp#t 68 6 9 @ = >8 69=>=>@8 = 9 9 9 @ 6 8@ = > @ = > 6 8 9 @ > invalid Inp#t =66 8 6 9 @ = >88 66 9 = > = > @ 8 6= 9 9 9 @ 6 8@ = > @ @= > 6 8 9 @ >

## +athe,atical notation Translation

"y,bol used 7 6asterisk8 Q 6slash8 Operation perfor,ed L#ltiplication Civision Precedence Bighest Bighest Bighest \$owest lowest

## Department of CSE and IT, JUIT Waknaghat

Infix notation
In this notation, the operator sym(ol is placed (etween its two operands. -o add ' to 4 we can write as ';4 or 4;' -o s#(tract C from R we write as R/C, (#t we can not write C/R as this operation is not comm#tative. In this notation we m#st disting#ish (etween 6';48QR and ';64QR8

## &olish 6prefix8 notation

In this notation, named after the polish mathematician San \$#kasiewieA, the operator sym(ol is placed (efore its two operands. -o add ' to 4 we write as ;'4 or ;4' -o s#(tract C from R we have to writ as NRC not as /CR

## Infix to polish notation

In order to translate an arithmetic expression in infix notation to polish notation, we do step (y step #sing rackets 6=>8 to indicate the partial translations. Ronsider the following expression in infix notation) 6'/4QR876'7T/\$8 -he partial translation may look like) 6'/=Q4R>876=7'T>/\$8 =/'Q4R>7=/7'T\$> 7/'Q4R/7'T\$ -he f#ndamental property of polish notation is that the order in which the operations to perform is completely determined (y the position of the operators and operands in the expression. 'ccordingly one never needs parenthesis when writing expression in polish notation.

## 3everse &olish 6&ostfix8 "otation

In this notation the operator sym(ol is placed after its two operands. -o add ' to 4 we can write as '4; or 4'; -o s#(tract C from R we have to write as RC/ not as CR/.

## Infix to reverse polish notation

Ronsider the following expression in infix notation) 6'/4QR876'QT/\$8 -he partial translation may look like)> 6'/=4RQ>876='TQ>/\$8 ='4RQ/>7='TQ\$/> '4RQ/'TQ\$/7

## Oval#ating Lathematical Oxpressions

Uenerally we #se infix notation, where one can not tell the order in which the operator sho#ld (e applied (y looking at the expression. -he expression in postfix notation is very easy to eval#ate, as the operands appear (efore the operator, there is no need of operator precedence or parentheses for operation. In order to eval#ate a postfix expression it is scanned from left to right. 's operands are enco#ntered, they are p#shed on a stack. *hen an operator enco#ntered, pop top one or two operands depending on the operator, perform the operation and place the res#lt (ack on the stack.

## Infix to postfix proced#re

Ronsider the following infix expression V) 61/,8762Q28
Rharacter scanned 6 1 / , 8 7 6 2 Q 2 8 Ond of expression stack 6 6 6/ 6/ empty 7 76 76 76Q 76Q 7 Ompty Oxpression p

## Oval#ating expression in postfix notation

Ronsider the following postfix expression p) 1,N22Q7
Rharacter Scanned 1 , / 2 2 Q 7 Ond of expression Stack 1 1, 2 22 222 2 +., 2 2

STUDENT T S?S"
1. W!A that im"lements the infi7 to "ostfi7 notation. 4he "rogram should read an infi7 string consists of single al"habetic characters for variables2 "arentheses2 and the )2F2G2 and + o"erators% call the conversion function% and then "rint the resulting "ostfi7 e7"ression. 4o test \$our "rogram transforms the following e7"ression with \$our "rogram% a. /FC). b. !GC).G/ c. >!)C?G.F/GF). :A Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat 2. W!A to im"lement the "ostfi7 evaluation. 4he "rogram should read a "ostfi7 string consisting of onl\$ multidigit numeric data and the )2 F2 G2 and + o"erators% call the evaluation function and then "rint the result. !fter each evaluation it should loo" and "rocess another evaluation. 1valuate the following e7"ressions with \$our "rogram: 25 0 G 1& F * ) 1 2& 3 ) G &1 F 2 30 & ) G 15 F

## Department of CSE and IT, JUIT Waknaghat

Practical No.11
_______________________________________________________________________ _ I!" Getting acquainted with Wueues.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to create queue. enqueue an dequeue.

F5e5e"
A queue is a line of persons waiting for their turn at some service counter. &ervice counter can be a tic>eting window of a cinema hall or tic>eting window of railway station etc. Eepending on the type of service provided by the service counter and number of person interested in service. there could be queue of varying lengths. The service at the service counter is provide on the first come first serve 'Q%Q&( basis. i.e.. in order of their arrival in the queue.
4#s Stop

S#ppose that at service co#nter, t1 #nits time is needed to provide a service to a single person and on average a new person arrive at the co#nter in t2 #nits of time. -he following possi(ilities may arise) 1. If t1Wt2, then the service co#nter will (e free for some time (efore a new person arrives at the service co#nter. Bence no V#e#e in this case. 2. If t1:t2, then service co#nter will (e (#sy for some time even after the arrival of a new person. -herefore this person has to wait for some time. Similarly other persons arriving at the service co#nter have to wait. Bence a V#e#e will (e formed. . If t1?t2, then as a person leaves the service co#nter, a new person arrives at the service co#nter. Bence no V#e#e in this case also.

## Department of CSE and IT, JUIT Waknaghat

Definition
' V#e#e is a linear list in which insertion can take place at one end of the list, called the rear of the list, and deletion can take place at other end called front of the list. 4ehavior of the V#e#e is FIFK system. In V#e#e terminology insertion and deletion operations are known as enV#e#e and deV#e#e operations.

## M#e#e which can accommodate maxim#m of 10 elements

0 1 2 + , 0 1 . 2

,
front 0

12

12
front

2
rear

## Department of CSE and IT, JUIT Waknaghat

Operations on -ueues
-he following operations are performed on V#e#es) Create -ueue\$-%.to create V#e#e as an empty V#e#e. /n-ue\$-0i%.to insert element I in a V. De-ueue\$-%.to access and remove an element of V#e#e V. Peek\$-%.to access the first element of the V#e#e V witho#t removing it. 1sfull\$-%.to check whether the V#e#e V is f#ll. 1se,pty\$-%.to check whether the V#e#e V is empty.

## 3epresentation of V#e#es in memory

'rray representation \$inked list representation

## Department of CSE and IT, JUIT Waknaghat

2rray representation
-he following are the necessary declaration) 3define C2P2C1T4 56 typedef struct { int front; int rear; int ele,ents7C2P2C1T48; !-ueue; -ueue -; In addition to a(ove decoration we will #se the declaration typedef enu, {false0 true ! 9oolean;

## 2rray representation of linear -ueue

0 /1 front /1 rear 0 0 front + rear 0 2 front + rear 3epresentation of V#e#e in memory 1 2 + , 0 1 . 2 1 2 + , 0 1 . 2

1
1

12 .
2

2
+ , 0 1 . 2

12 .

## &ro(lems with linear V#e#e

0 2 front 2 rear 1 2 + , 0 1 . 2

12 .

10 11 20

## 3epresentation of V#e#e in memory

It is not possi(le to enV#e#e more elements as s#ch, tho#gh two position in the linear V#e#e are vacant. -o overcome this pro(lem, the elements of the V#e#e are moved forward, so that the vacant positions are shifted toward the rear end. 0 1 2 + , 0 1 . 2 0 front 1 rear

12 .

10 11 20

## 3epresentation of V#e#e in memory

-his diffic#lty of managing front and rear can (e overcome if we treat the V#e#e position with index 0 as a position that comes after position with index 2 i.e., we treat the V#e#e as circ#lar.
+ ,

Rirc#lar V#e#e

/1 front

/1 rear

0 1 1 . 2 0

## Department of CSE and IT, JUIT Waknaghat

3epresentation of a V#e#e

+ , 2 . 2 12 0 front + rear 1 . 2 0 1 , 0 1

3epresentation of a V#e#e

+ , 2 . 2 12 2 front + rear 1 . 2 0 0 1

## Department of CSE and IT, JUIT Waknaghat

3epresentation of a V#e#e

+ , 2 2 front 2 rear 1 0 1 10 11 . 20 2 0 2 . 2 12

3epresentation of a V#e#e

+ , 2 0 1 10 1 11 . 20 00 0 2 . 2 12

2 front

0 rear

## 1,ple,entation of operations on a linear -ueue

Creatin: an e,pty -ueue; 4efore we can #se a V#e#e, it m#st (e created. 's the index of array element can take place in (etween 0 to R'&'RI-X/1 -he p#rpose of initialiAing the V#e#e is served (y assigning val#e /1 6sentinel val#e8 to front and rear varia(les. #oid create-ueue\$-ueue *p-% { p-)*front'p-)*rear')5; !

## -esting the V#e#e for #nderflow

4oolean isempty6V#e#e 7pV8 9 if6pV/:front??/18 ret#rn tr#e< else ret#rn false< @

## -esting the V#e#e for overflow

4oolean isf#ll6V#e#e 7pV8 9 if66pV/:front??08YY6pV/:rear??R'&'RI-X/188 ret#rn tr#e< else ret#rn false< @

## OnV#e#e operation on linear V#e#e

-here are two conditions, which can occ#r, even if the V#e#e is not f#ll) 1. If a linear V#e#e is empty, then the val#e of the front and the rear varia(le will (e "I\$ 6sentinel val#e8, then (oth front and rear are set to 0. 2. If the linear V#e#e is not empty, then there are f#rther two possi(ilities)
1. If the val#e of the rear varia(le is less than R'&'RI-X/1, then the rear varia(le is incremented. 2. If the val#e of the rear varia(le is eV#al to R'&'RI-X/1, then the elements of the linear V#e#e are moved forward, and the front and rear varia(les are adJ#sted accordingly.

## OnV#e#e operation on linear V#e#e

5oid enV#e#e6V#e#e 7pV, int val#e8 9 int I< if6isempty6pV88 pV/:front?pV/:rear?0< else if 6pV/:rear??R'&'RI-X/18 9 for6i?pV/:front<iW?pV/:rear<i;;8 pV/:elements=i/pV/:front>?pV/:elements=i>< pV/:rear?pV/:rear/pV/:front;1< pV/:front?0< @ else 9 pV/:rear;;< @ pV/:elements=pV/:rear>?val#e< @

## CeV#e#e operation on linear V#e#e

-here are two possi(ilities) 1. If there was only one element in the linear V#e#e, then after deV#e#e operation V#e#e will (ecome empty. -his state of linear V#e#e is reflected (y setting front and rear varia(les to /1, the sentinel val#e. 2. Ktherwise the val#e of front varia(le is incremented.

## CeV#e#e operation on linear V#e#e

Int deV#e#e6V#e#e 7pV8 9 int temp< temp?pV/:elements=pV/:front>< if6pV/:front??pV/:rear8 pV/:front?pV/:rear?/1< else pV/:front;;< ret#rn temp< @

## 'ccessing the front element

Int peek6V#e#e 7pV8 9 ret#rn 6pV/:elements=pV/:front>8 @

## Li,itation of Linear <ueue

If the last position of the V#e#e is occ#pied, it is not possi(le to enV#e#ing any more elements even tho#gh some positions are vacant towards the front positions of the V#e#e.

## 1,ple,entation of operations on a circular -ueue

Testin: a circular -ueue for o=erflow; Two conditions are;
N \$front'6% and \$rear'capacity)5% N front'rear>5 1f any of these two condition is satisfied0 it ,eans circular -ueue is full?
9oolean isfull\$-ueue *p-% { 1f\$\$\$p-)*front''6%@@\$p-)*rear''C2P2C1T4)5%%AA\$p-)*front''p-)*rear>5%% return true; else return false; !

## OnV#e#e operation on circ#lar V#e#e

-here are three conditions, which can occ#r, even if the V#e#e is not f#ll) 1. If a V#e#e is empty, then the val#e of the front and the rear varia(le will (e "I\$ 6sentinel val#e8, then (oth front and rear are set to 0. 2. If the V#e#e is not empty, then the val#e of the rear will (e the index of the last element of the V#e#e, then the rear varia(le is incremented. . If the V#e#e is not f#ll and the val#e of the rear varia(le is eV#al to capacity /1then rear varia(le is set to 0.

## OnV#e#e operation on circ#lar V#e#e

5oid enV#e#e6V#e#e 7pV, int val#e8 9 Q7adJ#st rear varia(le7Q if6pV/:front??/18 pV/:front?pV/:rear?0< else if 6pV/:rear??R'&'RI-X/18 pV/:rear?0< else pV/:rear;;< Q7store element at new rear 7Q pV/:elements=pV/:rear>?val#e< @

## CeV#e#e operation on circ#lar V#e#e

-here are two possi(ilities) 1. If there was only one element in the circ#lar V#e#e, then after deV#e#e operation V#e#e will (ecome empty. -his state of circ#lar V#e#e is reflected (y setting front and rear varia(les to /1, the sentinel val#e. 2. If the val#e of front varia(le is eV#al to R'&'RI-X/1, then set front varia(le to 0. If none of the a(ove conditions hold, then the front varia(le is incremented.

## CeV#e#e operation on circ#lar V#e#e

Int deV#e#e6V#e#e 7pV8 9 int temp< Q7store the front element in the temporary varia(le 7Q temp?pV/:elements=pV/:front>< Q7adJ#st front varia(le 7Q if6pV/:front??pV/:rear8 pV/:front?pV/:rear?/1< else if6pV/:front??R'&'RI-X/18 pV/:front?0< else pV/:front;;< Q7ret#rn the deV#ed element7Q ret#rn temp< @

## Bepresentin: a -ueue usin: a linked list

\$imitations of array (ased representation) SiAe of the V#e#e m#st (e known in advance *e may come across the sit#ation when an attempt to enV#e#e an element ca#ses overflow. Bowever , V#e#e as an a(stract data str#ct#re can not (e f#ll. Implementing V#e#e as an array prohi(its the growth of V#e#e (eyond the finite n#m(er of elements.

V Front rear

12

V Front rear

12

V Front rear

12

10

11

## \$inked list representation

-ypedef str#ct nodetype 9 int info< str#ct nodetype 7next< @node< -ypedef str#ct 9 node 7front< node 7rear< @V#e#e< M#e#e V< Bere I have defined two data type named node and V#e#e.

## Implementation of operation on a linear V#e#e

Rreating an empty V#e#e)

## -esting V#e#e for #nderflow

(oolean isempty6V#e#e 7pV8 9 if6pV/:front??"%\$\$8 ret#rn tr#e< else ret#rn false< @

## -esting V#e#e for overflow

Since a V#e#e is represented #sing a linked list can grow a limit of comp#terDs memory, therefore overflow condition never occ#r.

## Department of CSE and IT, JUIT Waknaghat

OnV#e#e operation
void enV#e#e6V#e#e 7pV, int val#e8 9 node 7ptr< ptr?6node78malloc6siAeof6node88< ptr/:info?val#e< ptr/:next?"%\$\$< if6pV/:rear??"%\$\$8 Q7V#e#e initially empty7Q pV/:front?pV/:rear?ptr< else 6pV/:rear8/:next?ptr< pV/:rear?ptr< @

CeV#e#e operation
Int deV#e#e6V#e#e 7pV8 9 int temp< node 7ptr< temp?6pV/:front8/:info< ptr?pV/:front< if6pV/:front??pV/:rear8 Q7only one element7Q pV/:front?pV/:rear?"%\$\$< else pV/:front?6pV/:front8/:next< free6ptr8< ret#rn temp< @

## 'ccessing the front element

Int peek6V#e#e 7pV8 9 ret#rn 66pV/:front8/:info8< @

Cisposing a V#e#e
5oid disposeV#e#e6V#e#e 7pV8 9 node 7ptr< while6pV/:frontZ?"%\$\$8 9 ptr?pV/:front< pV/:front?6pV/:front8/:next< free6ptr8< @ pV/:rear?6node78"%\$\$< @

STUDENT T S?S"
1. Write a menu driven "rogram to im"lementing the various o"erations on a linear queue. 2. Write a menu driven "rogram to im"lementing the various o"erations on a .ircular queue. 3. Write a menu driven "rogram to im"lementing the various o"erations on a queue re"resented using a lin#ed list. Harious o"eration are% enqueue data into queue <! Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat dequeue and "rint data "rint data at the front "rint data at the rear "rint entire queue "rint queue status: em"t\$ "rint queue status : full "rint number of elements.

## Department of CSE and IT, JUIT Waknaghat

Practical No.11
_______________________________________________________________________ _ I!" Getting acquainted with Applications of queues in e7pression evaluation.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to evaluate prefi7 e7pression.

STUDENT T S?S"
1. Ine wa\$ to evaluate a "refi7 e7"ression is to use a queue. 4o evaluate the e7"ression2 scan it re"eatedl\$ until \$ou #now the final e7"ression value. In each scan read the to#ens and store them in a queue. In each scan re"lace an o"erator that is followed b\$ two o"erands with their calculated values. For e7am"le2 the following e7"ression is a "refi7 e7"ression that is evaluated to 15D P ) G D ) 2 8 G ) & 8 * 3 we scan the e7"ression and store it in a queue. /uring the scan when an o"erator is followed b\$ two o"erands2 such as ) 2 8 2 we "ut the result 1@ in the queue after the first scan we have P ) G D 1@ G 12 * 3 after the second scan we have P ) D@ 02 3 after the third scan we have P 1*2 3 after the fourth scan we have 15D &rite a c pro'ram to eva\$uate a pre#i( e(pression.

## Department of CSE and IT, JUIT Waknaghat

Practical No.10
_______________________________________________________________________ _ I!" Getting acquainted with Trees. 9inary trees and 9&T..

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to create binary tree or 9&T. traverse binary tree or 9&T 'prePorder. inPorder. postPorder(. inserting. deleting. searching. and finding height in binary tree or 9&T.

-3OO COFI"OC
' tree - is a finite non empty set of elements. Kne of these elements is called the root, and the remaining elements, if any, are portioned into trees, which are called the s#( trees of -.

## Department of CSE and IT, JUIT Waknaghat

Introd#ction to -ree
F#ndamental data storage str#ct#res #sed in programming. Rom(ines advantages of an ordered array and a linked list. Searching as fast as in ordered array. Insertion and deletion as fast as in linked list.

-ree characteristics
Ronsists of nodes connected (y edges. "odes often represent entities 6complex o(Jects8 s#ch as people, car parts etc. Odges (etween the nodes represent the way the nodes are related. Its easy for a program to get from one node to another if there is a line connecting them. -he only way to get from node to node is to follow a path along the edges.

## Department of CSE and IT, JUIT Waknaghat

-ree -erminology
Boot; node witho#t parent 6'8 1nternal node; node with at least one child 6', 4, R, F8 / ternal node 6a.k.a. leaf 8) node witho#t children 6O, I, S, T, U, B, C8 2ncestors of a node; parent, grandparent, grand/grandparent, etc. Depth of a node) n#m(er of ancestors E Cei:ht of a tree; maxim#m depth of any node 6 8 Descendant of a node; child, grandchild, grand/grandchild, etc. De:ree of an ele,ent; no. of children it has "ubtree; tree consisting of a node and its descendants
A

subtree
I J K

-ree -erminology
Path; -raversal from node to node along the edges res#lts in a seV#ence called path. Boot; "ode at the top of the tree. Parent; 'ny node, except root has exactly one edge r#nning #pward to another node. -he node a(ove it is called parent. Child; 'ny node may have one or more lines r#nning downward to other nodes. "odes (elow are children. Leaf; ' node that has no children. "ubtree; 'ny node can (e considered to (e the root of a s#(tree, which consists of its children and its childrenDs children and so on.

## Department of CSE and IT, JUIT Waknaghat

-ree -erminology
#isitin:; ' node is visited when program control arrives at the node, #s#ally for processing. Tra=ersin:; -o traverse a tree means to visit all the nodes in some specified order. Le=els; -he level of a partic#lar node refers to how many generations the node is from the root. 3oot is ass#med to (e level 0. Deys; Tey val#e is #sed to search for the item or perform other operations on it.

4inary -rees
Overy node in a (inary tree can have at most two children. -he two children of each node are called the left child and right child corresponding to their positions. ' node can have only a left child or only a right child or it can have no children at all.

## Department of CSE and IT, JUIT Waknaghat

4inary -rees
' (inary tree is a tree with the following properties)
N Oach internal node has at most two children 6exactly two for proper (inary trees8 N -he children of a node are an ordered pair

'pplications)
N arithmetic expressions N decision processes N searching
A

*e call the children of an internal node left child and right child 'lternative rec#rsive definition) a (inary tree is either
N a tree consisting of a single node, or N a tree whose root has an ordered pair of children, each of which is a (inary tree
D

## 'rithmetic Oxpression -ree

4inary tree associated with an arithmetic expression
N internal nodes) operators N external nodes) operands

## &roperties of &roper 4inary -rees

"otation
n n#m(er of nodes e n#m(er of external nodes i n#m(er of internal nodes h height

## &roperties) # e=i+! # n = "e ! # hi # h 'n !(/" # e "h

TB//"
4inary Search -rees) ' (inary search tree - is a (inary tree that may (e empty. ' non empty (inary search tree satisfies the following properties) 1. Overy element has a key 6or val#e8 and no two elements have the same key i.e. all keys are #niV#e. 2. -he keys, if any, in the left s#(tree of the root are smaller than the key in the node. . -he keys, if any, in the right s#(tree of the root are larger than the key in the node. +. -he left and right s#(trees of the root are also (inary search trees.

## Department of CSE and IT, JUIT Waknaghat

9"T
10 00 1, .0 22 10 +0 ,, 1, 10 .0 22

02

12

Fig.6a8

Fig. 6(8

Fig. [

## Bepresentation of 9inary @ 9"T

'rray 3epresentation \$inked list representation

## Department of CSE and IT, JUIT Waknaghat

'rray 3epresentation
For simplicity , I am considering the array is indexed with an index set (eginning from 1 not 0.
1 10 2 00 .0 + 0 , 02 0 1, 1 22

1 +0

'rray representation of 4S- in fig 6a8 2 + , 0 10 ,, , 12 'rray representation of 4S- in fig 6(8 2 + , 0 .0 1, 'rray representation of 4S- in fig 6c8

1 10

1 22

## Department of CSE and IT, JUIT Waknaghat

-his scheme of representation is V#ite wastef#l of space when (inary tree is skewed or n#m(er of elements are small as compared to its height. 'rray representation is #sef#l only when the (inary tree is f#ll or complete.

## Department of CSE and IT, JUIT Waknaghat

-he most pop#lar and practical way of representing a (inary tree is #sing links 6pointers8.
10

00

.0

0 !

! 02 !

! 1, !

! 22 !

## \$inked representation of (inary search tree of fig#re 6a8

2rray Bepresentation
In this representation the (inary tree is represented (y storing each element at the array position corresponding to the n#m(er assigned to each n#m(er 6nodes8 In this representation, a (inary tree of height h reV#ires an array of siAe 62h/18, in the worst case

## Department of CSE and IT, JUIT Waknaghat

\$inked representation
! 10

.0

! 1, !

! 22 !

## \$inked representation of (inary search tree of fig#re 6c8

\$inked representation
! 10

! 12

! .0

! ., !

## Department of CSE and IT, JUIT Waknaghat

\$inked 3epresentation
In linked representation, each element is represented (y a node that has exactly two link fields. Field names are left and right. Oach node has data field called info. -he node str#ct#re is defined as) str#ct nodetype 9 str#ct nodetype 7left< int info< str#ct nodetype 7right< @<

## Implementation of (inary tree will consider following declarartion

typedef str#ct nodetype 9 str#ct nodetype 7left< int info< str#ct nodetype 7right< @4S-< 4S- root< Bere , I have defined a new datatype and given it name 4S-, then I have declared a pointer varia(le root to represent the (inary 6search8 tree.

## Rommon operation on (inary and (inary search trees

Some of the operations that are commonly performed on (inary as well as (inary search trees) Rreating an empty tree. -raverse it Cetermine its height. Cetermine the n#m(er of elements in it. Cetermine the no of internal nodes i.e. non leaf nodes. Cetermine the no of external nodes i.e. leaf nodes. Cetermine its mirror image. 3emove it from memory.

## Kperations that are performed on only with (inary search trees

1. 2. . +. ,. Insert a new node. Search an element. Find the smallest element. Find the largest element. Celete a node.

## 1. Rreating an empty 4inary 6Search8 -rees

void createtree64S- 77tree8 9 7tree?"%\$\$< @

## 2. -raverse a (inary tree

&reorder 6 depth first order 8
1. 5isit the root 2. -raverse the left s#(tree in preorder. . -raverse the right s#(tree in preorder.

## Inorder 6Symmetric order 8

1. -raverse the left s#(tree in inorder. 2. 5isit the root. . -raverse the right s#(tree in inorder.

## -raverse a (inary tree

&ostorder
1. -raverse the left s#(tree in postorder. 2. -raverse the right s#(tree in postorder. . 5isit the root.

## Tra=ersin: of 9inary \$search% tree

5? Pre)order Tra=ersal; void pre64S- 7tree8 9 if6treeZ?"%\$\$8 9 printf6FPdI,tree/:info8< pre6tree/:left8< pre6tree/:right8< @ @

1N)Order Tra=ersal
void inorder64S- 7tree8 9 if6treeZ?"%\$\$8 9 inorder6tree/:left8< printf6FPdI,tree/:info8< inorder6tree/:right8< @ @

## Department of CSE and IT, JUIT Waknaghat

Oxample
&re/order) ' 4 C O U B R F In order) C 4 U O B ' R F Craw the (inary tree -.

Oxample
Pre) Order; ' 3oot In) Order; 4 C U 4 C O U B R F

Oxample)
&artial -ree

'

\$-'

3-'

C 4 O B
4 C C 4 O U U O

## Pre) Order; 1n) Order;

B B

Oxample
Pre) Order; 4 3oot In) Order; C \$eft s#(tree \$-4 C O U B

Oxample)
&artial -ree
'

4 3-'

R
C

U O B

3-4

## Pre) Order; 1n) Order;

O U

U O

B B

Oxample
Pre) Order; O 3oot In) Order; U \$eft s#(tree \$-O U B

Oxample)
&artial -ree
'

4 3-'

R
C O

## Pre) Order; 1n) Order;

R R

F F

Oxample
Pre) Order; R 3oot In) Order; \$eft s#(tree \$-R F

Oxample)
'

## Cetermining the height of the (inary tree

Int height64S- 7tree8 9 int lheight,rheight< if6tree??"%\$\$8 9 ret#rn 0< @ else 9 lheight?height6tree/:left8< rheight?height6tree/:right8< if6lheight:rheight8 ret#rn ;;lheight< else ret#rn ;;rheight< @ @

## Cetermining n#m(er of nodesQelements

'ny of the traversal scheme can (e #sed to determine the n#m(er of element. -he approach we #se that is
N "#m(er of elements in the tree is eV#al to n#m(er of nodes in left s#( tree pl#s n#m(er of nodes in right s#( tree pl#s one.

## Cetermining n#m(er of nodesQelements

Int totalnodes64S- 7tree8 9 if6tree??"%\$\$8 ret#rn 0< else ret#rn 6totalnodes6tree/:left8;totalnodes6tree/:right8 ; 18< @

## Inserting a new element

If the (inary search tree is initially empty, then the element is inserted as root node. Ktherwise the element is inserted as terminal node. If the element is less than the element in the root node, then the element is inserted in the left s#( tree else right s#( tree.

4S,0 1,

2,

20

+0

00

.0

10

+,

0,

.,

## Inserting a new element

5oid insertelement64S- 7tree, int element8 9 4S- 7ptr,7nodeptr,7parentptr< ptr?64S-78malloc6siAeof64S-88< ptr/:info?element< ptr/:left?ptr/:right?"%\$\$< if6tree??"%\$\$8 7tree?ptr< else 9 parentptr?"%\$\$< nodeptr?7tree< while6nodeptrZ?"%\$\$8 9 parentptr?nodeptr< if6elementWnodeptr/:info8 nodeptr?nodeptr/:left< else nodeptr?nodeptr/:right< @ if6elementWparentptr/:info8 parentptr/:left?ptr< else parentptr/:right?ptr< @ @

## Department of CSE and IT, JUIT Waknaghat

Searching an element
-he element in (inary search tree can (e searched very V#ickly. Search operation on (inary tree is similar to applying (inary search techniV#e to a sorted linear array. -he element to (e searched will (e compared with root node. If matches with the root node then search terminates here. Ktherwise search is contin#ed in the left s#( tree if the element is less then the root or in the right s#( tree if the element is greater then the root.

## Cetermining the height of the (inary tree

*e find the height of the left s#( tree and right s#( tree of given node. Beight of the (inary tree at a given node will (e eV#al to maxim#m height of the left and right s#( tree pl#s 1. &rogram in the next slide shows the implementation of vario#s steps reV#ired.

## -he Find KperationH

Droot <

"

!A

&uppose I try to find the node with H in it. Qirst go down the right subtree. then go down the left subtree.

Searching an element
4S- searchelement64S- 7tree, int val#e8 9 if66tree/:info??val#e8\\tree??"%\$\$8 ret#rn tree< else if6val#eWtree/:info8 ret#rn searchelement6tree/:left, val#e8< else ret#rn searchelement6tree/:right, val#e8< @

## Finding smallest node

4eca#se of the property of (inary search tree, we know that the smallest node in the tree will (e one of the nodes in the left s#( tree, if it exists< otherwise node itself will (e the smallest node. 4S- smallest64S- 7tree8 9 if66tree??"%\$\$8\\6tree/:left??"%\$\$88 ret#rn tree< else ret#rn smallest6tree/:left8< @

## -he FindLin KperationH

Droot <

"

!A

Thi) f5nction ret5rn) a pointer to the node containing the )malle)t element in the tree. It doe) )o 67 folloCing the left )ide of the tree.

## Finding largest node

4eca#se of the property of (inary search tree, we know that the largest node in the tree will (e one of the nodes in the right s#( tree, if it exists< otherwise node itself will (e the largest node. 4S- largest64S- 7tree8 9 if66tree??"%\$\$8\\6tree/:right??"%\$\$88 ret#rn tree< else ret#rn largest6tree/:right8< @

## -he FindLax KperationH

Droot <

"

!A

Thi) f5nction ret5rn) a pointer to the node containing the large)t element in the tree. It doe) )o 67 folloCing the right )ide of the tree.

## Department of CSE and IT, JUIT Waknaghat

Deletin: a node
-o delete a node, the following possi(ilities may arise) Node is ter,inal node) in this case if node is left child of its parent, then the left pointer of its parent is set to "%\$\$, otherwise it will (e right child of its parent and accordingly pointer of its parent is set to "%\$\$. Node ha=in: only one child; in this case, the appropriate pointer of its parent is set to child, th#s (y passing it. Node ha=in: two children; predecessor replaces node val#e, and then the predecessor of node is deleted.

4S,0 1,

2,

20

+0

00

.0

10

+,

0,

.,

4S,0

2,

20

+0

00

.0

10

+,

0,

.,

## E6GFE proceed ri:ht 0 delete FE

4S,0 .0

2,

20

+0

00

10

+,

0,

.,

"ince node has both ri:ht and left child0 if ri:ht sub tree is opted find the s,allest node0 if left sub tree is opted find the lar:est node

## Department of CSE and IT, JUIT Waknaghat

4S,0 .0

2,

20

+0

00

.,

10

+,

0,

"ince node has child0 if ri:ht sub tree is opted find the s,allest node0 if left sub tree is opted find the lar:est node

## Department of CSE and IT, JUIT Waknaghat

4S-) Celetion
Deleting a node with one hild

Before delete(4)

## 4S-) Celetion 6contd.8

Deleting a node with two hildren

After delete%2&

Before delete(2)

Deletion !trateg"# 'e\$la e the node with s(allest node in the right subtree

## Department of CSE and IT, JUIT Waknaghat

4S,0 .0

2,

20

+0

00

.,

10

+,

0,

"ince node)*ri:ht'node)*left'N(LL0 delete the node and place N(LL in the parent node

## -he 3emoval Kperation

If the node to (e removed is a leaf, it can (e deleted immediately. If the node has one child, the node can (e deleted after its parent adJ#sts a link Droot to (ypass the deleted node.
< Chat if the " is deletedV "

!A

## Department of CSE and IT, JUIT Waknaghat

3emovalH
Droot < t " t right ; H !A ; H !A R " R < Droot

&et t 3 t right

3emovalH
If the node to (e removed has two children, the general strategy is to replace the data of this node with the smallest data of the right s#(tree. -hen the node with the smallest data is now removed 6this case is easy since this node cannot have two children8.

## Department of CSE and IT, JUIT Waknaghat

3emovalH
Remove the " againX Droot < < Droot

"

!A

!A

5 :

5 :

## -he 3emoval Kperation

8oid remo8e 9con)t int G(, \$inar7Node -Gt: con)t ; if 9 t ,, NU'' : ret5rn2 44 Item not fo5nd2 do nothing if 9 ( H t element : remo8e9 (, t left :2 el)e if9 t element H ( : remo8e9 (, t right :2 el)e if9 t left +, NU'' GG t right +, NU'' : 44 TCo children ; t element , find!in9 t right : element2 remo8e9 t element, t right :2 = el)e ; \$inar7Node -oldNode , t2 t , 9 t left +, NU'' : I t left " t right2 delete oldNode2 = = 44 #ne child

STUDENT T S?S"
1. Write a com"lete menu driven "rogram to demonstrate the use of the different o"erations discussed in the binar\$ tree descri"tion. For e7am"le P creation P traversal o "re o in o "ost P deletion P searching RK Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat 2. Write a function to "erform the level order traversal of a binar\$ search tree. 5. Write a function to find the "redecessor and successor of a given element.

## Department of CSE and IT, JUIT Waknaghat

Practical No.1/
_______________________________________________________________________ _ I!" Getting acquainted with &orting 'Insertion and &election &ort(.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to arrange the elements in an ascending or descending order.

Sorting"
&orting is the process of arranging the elements in some logical order. ? &orting are classified into following categories6 ? E(ternal )orting" ? deals with sorting of the data stored in data files. This method is used when the volume of data is very large and cannot be held in computer main memory. ? Internal )orting" ? deals with sorting the data held in memory of the computer

Selection Sort"
The selection sort also requires 'nP!( passes to sort an array. In the first pass. find the smallest element from elements a@AB. a@!B. a@"B.X... a@nP!B and swap with the first element. i.e. a@AB. In the second pass. find the smallest element from elements a@!B. a@"B. a@5B.. a@nP!B and swap with a@!B and so on. Pa))1. ? Qind the location loc of the smallest element in the entire array. i.e. a@AB.@!B.a@"BX a@nP!B ? Interchange a@AB 2 a@locB. Then a@AB is trivially sorted. Pa))0. ? Qind the location loc of the smallest element in the entire array. i.e. a@!B.a@"BX a@nP!B ? Interchange a@!B 2 a@locB. Then a@AB. a@!B are sorted. Pa))k. ? Qind the location loc of the smallest element in the entire array. i.e. a@>B.a@>Y!B.a@>Y"BXa@nP!B ? Interchange a@>B 2 a@locB. Then a@AB.a@!B.a@"B.Xa@>B are sorted. Pa))n<1. ? Qind the location loc of the smaller of the element a@nP"B.a@nP!B ? Interchange a@nP"B 2 a@locB. Then elements a@AB.a@!B.a@"BX.a@nP!B.

E& !P'E"
Given array6 "A 5; :A !AA 5 !A !; a@AB a@!B a@"B a@5B a@:B a@;B a@<B !AA Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

"A

5;

a@"B :A

a@5B !AA

a@:B 5

a@;B !A

a@<B !;

"election "ort
Pass H

\$oc?,

\$oc?0

Pass I

\$oc?+

"election "ort
Pass E

## a=0> a=1> a=2> a= > a=+> a=,> a=0> 10 1, 20 100 , +0

Interchange elements a=+> Y a=,> i.e. 100 and ,

\$oc?,

Pass J

## a=0> a=1> a=2> a= > a=+> a=,> a=0> 10 1, 20 , 100 +0

Interchange elements a=,> Y a=0> i.e. 100 and +0

\$oc?0

## Department of CSE and IT, JUIT Waknaghat

'lgorithm
Smallestelement6a,n,k,loc8 Bere a is linear array of siAe n. this s#( algorithm finds the location loc of smallest element among a=k/1>,a=k;1>,a=k;2>Ha=n/1>. -emporary varia(le small is #sed to hold the c#rrent smllest element nd J is #sed loop control varia(le. 4egin set small?a=k/1> set loc?k/1 for J?k to 6n/18 (y 1 do if6a=J>Wsmall8 then set small ? a=J> set loc?J endif endfor end

'lgorithm
Selectionsort6a,n8 Bere a is the linear array with n elements in memory. -his algorithm sorts elements into ascending order. It #ses a temporary varia(le temp to facilitate the exchange of two val#es and varia(le I is #sed loop control varia(le 4egin for i?1 to 6n/18 (y 1 do call smllest element6a,n,I,loc8 set temp?a=i/1> set a=i/1>?a=loc> set a=loc>?temp endfor end

## Department of CSE and IT, JUIT Waknaghat

1nsertion sort
-his algorithm is very pop#lar with (ridge players when they sort their cards. In this proced#re, we pick #p a partic#lar val#e and then insert it at the appropriate place in the sorted s#( list. -his algorithm also reV#ires n/1 passes

1nsertion sort
Pass5) a=1> is inserted either (efore or after a=0> so that a=0> and a=1> are sorted. PassH; a=2> is inserted either (efore a=0> or (etween a=0> and a=1> or after a=1> so that the elements a=0>, a=1>, a=2> are sorted. Pass3; a= > is inserted either (efore a=0> or (etween a=0> and a=1> or (etween a=1> and a=2> or after a=2> so that the elements a=0>, a=1>, a=2>, aa= > are sorted. Passk; a=k> is inserted in proper place in the sorted s#( array a=0>, a=1>, a=2>,Ha=k/1> so that the elements a=0>, a=1>, a=2>,Ha=k/1>,a=k> are sorted. Passn)5; a=n/1> is inserted in proper place in the sorted s#( array a=0>, a=1>, a=2>,Ha=n/2> so that the elements a=0>, a=1>, a=2>,Ha=n/1> are sorted.

## Department of CSE and IT, JUIT Waknaghat

/ a,ple
Uiven array) 20 , +0 100 a=0> 20
Pass 5;

a=1> , a=2> +0

a=0> ,

a=1> 20

a=,> 10

"election "ort
Pass H

Pass I

## a=0> a=1> a=2> a= > a=+> a=,> a=0> 20 , +0 100 10 1,

Since =+> is less than a= >,a=2>,aa=1> as well as a=0> therefore insert a=+> (efore a=0>

"election "ort
Pass E

## a=0> a=1> a=2> a= > a=+> a=,> a=0> 20 , +0 100 10 1,

Since =,> is less than a=+>,a= >,a=2>,a=1> therefore insert a=,> (efore a=1>

Pass J

## a=0> a=1> a=2> a= > a=+> a=,> a=0> 10 20 , +0 100 1,

Since =0> is less than a=,>, a=+>,a= >,a=2> therefore insert a=,> (efore a=2>

## a=0> a=1> a=2> a= > a=+> a=,> a=0> 10 1, 20 , +0 100

'lgorithm
insertionsort6a,n8 Bere a is the linear array with n elements in memory. -his algorithm sorts elements into ascending order. It #ses a temporary varia(le temp to facilitate the exchange of two val#es and varia(le J and k are #sed loop control varia(les. 4egin for k?1 to 6n/18 (y 1 do set temp?a=k> set a=J>?k/1 while66tempWa=J>8 and J:?08 do set a=J;1>?a=J> set J?J/1 endwhile set a=J;1>?temp endfor end

STUDENT T S?S"
1. !n arra\$ contains the elements shown below. =ort the elements b\$ insertion sort in ascending order2 what would be the value of the elements in the arra\$ after each "asses of the straight insertion sort algorithm. 3 13 0 2* && 23 D8 50 2. !n arra\$ contains the elements shown below. =ort the elements b\$ selection sort in ascending order2 what would be the value of the elements in the arra\$ after each "asses of the straight selection sort algorithm. 0 8 2* && 13 23 D8 50 3 3. 5odif\$ the e7ercise1 and e7ercise2 given above for sorting in descending order. !A; Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

## Department of CSE and IT, JUIT Waknaghat

Practical No. 1.
_______________________________________________________________________ _ I!" Getting acquainted with &orting '9ubble and Terge &ort(.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to arrange the elements in an ascending or descending order.

\$566le Sort"
? ? ? ? It requires nP! passes to sort an array. In each pass every element a@iB is compared with a@iY!B. for i3A to 'nP>(. where > is the pass number and if they are out of order i. e. if a@iB+a@iY!B. they are swapped. This will cause the largest element move up or bubble up. Thus after the end of the first pass the largest element in the array will be placed in the nth position and on each successive pass. the ne7t largest element is placed at position 'nP!(.'nP"(X.." respectively

Pa))1. &tep!. if a@AB+a@!B then swap a@AB and a@!B. &tep". if a@!B+a@"B then swap a@!B and a@"B. &tepnP!. if a@nP"B+a@nP!B then swap a@nP"B and a@nP!B. Pa))0. &tep!. if a@AB+a@!B then swap a@AB and a@!B. &tep". if a@!B+a@"B then swap a@!B and a@"B. &tepnP". if a@nP5B+a@nP"B then swap a@nP5B and a@nP"B. . . Pa)) k. &tep!. if a@AB+a@!B then swap a@AB and a@!B. &tep". if a@!B+a@"B then swap a@!B and a@"B. &tep nP>. if a@nP>Y!B+a@nP>B then swap a@nP>Y!B and a@nP>B. Pa)) n<1 &tep ! if a@AB+a@!B then swap a@AB and a@!B.

## Department of CSE and IT, JUIT Waknaghat

9ubble sort
Oxample) 12 +0 2 1,

12 +0 2 1,
Uiven array

12 +0 2 1,
Pass 5

12 +0 2 1,

12 2 +0 1,

12 2 1, +0

9ubble sort
2 2 12 1, +0 +0 2

12 1,

12 1, +0

&ass

pass +

'lgorithm
4#((lesort6a,n8 for k?1 to 6n/18 (y 1 do for J?0 to 6n/k/18 (y 1 do if6a=J>:a=J;1>8 then set temp?=J> set a=J>?a=J;1> set a=J>?temp endif endfor Ondfor end

!erge Sort"

## Lerge Sort 'lgorithm

Di=ide) If S has at least two elements 6nothing needs to (e done if S has Aero or one elements8, remove all the elements from S and p#t them into two seV#ences, S1 and S2 , each containing a(o#t half of the elements of S. 6i.e. S1 contains the first nQ2 elements and S2 contains the remaining nQ2 elements8. Con-uer) Sort seV#ences S1 and S2 #sing Lerge Sort. Co,bine) &#t (ack the elements into S (y merging the sorted seV#ences S1 and S2 into one sorted seV#ence

## Lerge Sort) 'lgorithm

Merge-Sort (A, Merge-Sort (A, p, p, r) r) if if p p< <r r then then q (p+r)/2 q (p+r)/2 Merge-Sort (A, Merge-Sort (A, p, p, q) q) Merge-Sort (A, q+1, Merge-Sort(A, q+1, r) r) Merge (A, Merge (A, p, p, q, q, r) r) Merge (A, Merge (A, p, p, q, q, r) r) Take the smallest Take the smallest of of the the two two topmost topmost elements elements of of sequences sequences A[p..q] A[p..q] and and A[q+1..r] A[q+1..r] and and put put into into the the resulting resulting sequence. sequence. Repeat Repeat this, this, until until both both sequences sequences are empt . !op the resulting sequence into are empt . !op the resulting sequence into A[p..r]. A[p..r].

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / 1

LergeSort 6Oxample8 / 2

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 /

LergeSort 6Oxample8 / +

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / ,

LergeSort 6Oxample8 / 0

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / 1

LergeSort 6Oxample8 / .

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / 2

LergeSort 6Oxample8 / 10

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / 11

LergeSort 6Oxample8 / 12

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / 1

LergeSort 6Oxample8 / 1+

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / 1,

LergeSort 6Oxample8 / 10

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / 11

LergeSort 6Oxample8 / 1.

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / 12

LergeSort 6Oxample8 / 20

## Department of CSE and IT, JUIT Waknaghat

LergeSort 6Oxample8 / 21

LergeSort 6Oxample8 / 22

## Lerge Sort 3evisited

-o sort n n#m(ers
N if n?1 doneZ N rec#rsively sort 2 lists of n#m(ers nQ2 and nQ2 elements N merge 2 sorted lists in 6n8 time

Strategy
N (reak pro(lem into similar 6smaller8 s#(pro(lems N rec#rsively solve s#(pro(lems N com(ine sol#tions to answer

STUDENT T S?S"
1. !n arra\$ contains the elements shown below. 4he first two elements have been sorted using a bubble sort. What would be the value of the elements in the arra\$ after three more "asses of the bubble sort algorithmJ Ese the version of bubble sort that start from the end and bubbles u" the smallest element. 0 8 2* && 13 23 50 D8 2. =how the result after each merge "hase when merging the following two files * 12 1D 23 3& 8 11 10 2@ 25 13 21 20 28 2D 0 3@ 3* 30 3D

## Department of CSE and IT, JUIT Waknaghat

Practical No. 1*
_______________________________________________________________________ _ I!" Getting acquainted with &orting 'Radi7 and Wuic> &ort(.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to arrange the elements in an ascending or descending order.

F5ick Sort"
? Another dividePandPconquer sorting algorithm ? To understand quic>Psort. let s loo> at a highPlevel description of the algorithm !( Eivide 6 If the sequence & has " or more elements. select an element 7 from & to be your pivot. Any arbitrary element. li>e the last. will do. Remove all the elements of & and divide them into 5 sequences6 =. holds & s elements less than 7 I. holds & s elements equal to 7 G. holds & s elements greater than 7 "( Recurse6 Recursively sort = and G 5( %onquer6 Qinally. to put elements bac> into & in order. first inserts the elements of =. then those of I. and those of G. Jere are some diagrams....

## Idea of M#ick Sort

18 "elect) pick an element

2% Di=ide) rearrange elements so that x goes to its final position O 8 Becurse and Con-uer) rec#rsively sort

## Department of CSE and IT, JUIT Waknaghat

In/&lace M#ick/Sort
Divide step: l scans the sequence from the left, and r from the right.

A swap is performed when l is at an element larger than the pivot and r is at one smaller than the pivot.

## A final swap with the pivot completes the divide step

2l:orith,
V#icksort6a , l, r8 4egin If6lWr8 then splitarray6a,l,r,loc8 V#icksort6a,l,loc/18 V#icksort6a,loc;1,r8 endif end

QQpartition the array QQrec#rsively sort left s#( array QQrec#rsively sort right s#( array

This method is used by the most of the of the people when sorting a list of names in alphabetical order. The procedure we follow is6 Qirst. the names are grouped according to the first letter. thus the names are arranged in "< classes. one for each letter of the alphabet.. first class consists of those names that begin with letter A. the second class consists of those names that begin with letter 9 . and so on. \$e7t. the names are grouped according to the second letter. After this step. the list of names will be sorted on first two letters. This process is continued for the number of times depending on the length of the names with ma7imum letters. If shorter names. we assume those names padded with blan>s. !"5 Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

## Department of CSE and IT, JUIT Waknaghat

E& !P'E"
Cho wantZs to sort bytesV [ouV I norally sort asciiPte7ts. floats or longints. 9ecause I only want to e7plain how the e7tenstion wor>s IZll go on with longints. If you want increase the si8e of the elements to sort you can do this in several ways. Iither you increase the si8e of inde7 and distribution or you sort in several passes. Increasing the si8e of the inde7 only wor>s for short values 'sorting smallints would require at least <;;5<D" bytes for inde7 and distribution list which finally needs ";< >b of memory.. I thin> this is to much 'only thin> about how long it ta>es to clear the memory and build the inde7Plist.. In this time quic>sort may have sorted your list already((. \$ow we need a clever way to sort more bits with the same memoryPamount. Ce can do this with several passes. =etZs do it in decimal.
unsorted list: 523 153 088 554 235 sorting for R di! 0 (le st signifi" nt digit) 523 153 554 235 088 # sorting for R di! 1 (2nd\$ signifi" nt digit) 523 235 153 554 088 # sorting for R di! 2 (%ost\$ signifi" nt digit) 088 153 235 523 554

STUDENT T S?S"
1. !n arra\$ contains the elements shown below. What would be the value of the elements in the arra\$ after each "ass of the quic# sort algorithmJ !lso mention the "ivot. 5 3 8 D 1 0 @ 2 * & 2. =ort the list 213 1&5 &5* 0@@ 515 2D5 *0& D25 using buc#et sort method.

## Department of CSE and IT, JUIT Waknaghat

Practical No.13
_______________________________________________________________________ _

## I!" Getting acquainted with &earching '=inear and binary(. #\$JECTI%E

The goal of this lab is to help you become acquainted with how to search an element in an array. &earching is the process of finding the location of given element in the linear array. The search is said to be successful if the given element is found i.e. . the element does e7ists in the array, otherwise unsuccessful. There are two approaches to search operation6 ? =inear search ? 9inary search

'inear Search"
? ? This method. which traverse a sequentially to locate item is called linear search or sequential search. The algorithm that one chooses generally depends on organi8ation of the array elements. if the elements are in random order. then one have to use linear search technique

lgorithm"
=inearsearch'a.n.item.loc( Jere a is the linear array of the si8e n. this algorithm finds the location of the elemnts item in linear array a. if search ends in success it sets loc to the inde7 of the element, otherwise it sets loc to P! 9egin for i3A to 'nP!( by ! do if'a@iB 3 item( then set loc3I e7it endif endfor set loc P! end

\$inar7 Search"
&uppose the elements of the array are sorted in ascending order. The best sorting algorithm. called binary search. is used to fined the location of the given element !"< Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

## Department of CSE and IT, JUIT Waknaghat

E& !P'E"
5.!A.!;."A.5;.:A.<A Ce want to search element !; Given array !. Ce ta>e the beg3A. end3< and compute location of the middle element as mid3'begYend(S" 3 'AY<(S"35 ". %ompare the item with mid i.e. a@midB3a@5B is not equal to !;. beg*end. Ce start ne7t iteration. 5. As a@midB3"A+!;. therefore. we ta>e end3midP!35P!3" where as beg remains same.. Thus mid3'begYend(S" 3 'AY"(S"3! &ince a@midB i.e. a@!B3!A*!;. therefore. we ta>e beg3midY!3!Y!3". where as end remains same &ince beg3end :. %ompute the mid element mid3'begYend(S"3'"Y"(S"3" &ince a@midB i.e. a@"B3!;. the search terminates on success.

lgorithm"
9inarysearch'a.n.item.loc( 9egin set beg3A set end3nP! &et mid3'begYend(S" while''beg*3end( and'a@midBN3item( do if'item*a@midB( then set end3midP! else set beg3midY! endif set mid3'begYend(S" endwhile if'beg+end( then set loc3P! else set loc3mid endif end

STUDENT T S?S"
1. !n arra\$ contains the elements shown below. Esing the binar\$ search algorithm2 trace the ste"s followed to find 88. !t each loo" iteration2 including the last2 show the contents of first2 last and mid. 18 13 10 2* && 5* 88 D0 2. !n arra\$ contains the elements shown below. Esing the binar\$ search algorithm2 trace the ste"s followed to find 2@. !t each loo" iteration2 including the last2 show the contents of first2 last and mid. !"H Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat 18 13 10 2* && 5* 88 D0 3. Write a "rogram that creates an arra\$ of 1@@ random integers in the range 1 to 2@@ and then2 using the sequential search2 searches the arra\$ 1@@ times using randoml\$ generated targets in the same range at the end of the "rogram2 dis"la\$ the following statistics% a. the number of searches com"leted b. the number of successful searches c. the "ercentage of successful searches d. the average number of tests "er search to determine the average number of test "er search2 \$ou need to count the number of tests for each search.

## Department of CSE and IT, JUIT Waknaghat

Practical No.1@
_______________________________________________________________________ _ I!" Getting acquainted with Jeap.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to create JIA\. and sort the array by using heap sort.

Ceaps
ObKecti=es; Cescri(e a heap Cescri(e how a heap can (e represented in memory Implement the vario#s operations on heap Cescri(e the applications of heaps

1ntroduction
Beap is (inary tree that satisfies the following properties) Shape property Krder property 4y the shape property we mean that heap m#st (e complete (inary tree. 4y order property we mean that every node in the heap, the val#e stored in that node is greater than or eV#al to the val#e in each of its children. ' heap that satisfy the a(ove property is known as ,a ? heap? if every node in the heap is less than or eV#al to the val#e in each of its children. that heap is known as ,in? heap?

## Department of CSE and IT, JUIT Waknaghat

Ceaps
20 , 21 2, +0 21 ,0

,0 +0

2,

20

Li:?\$a% +a ? heap

## Bepresentation of heap in ,e,ory

' heap is represented in memory #sing linear array i.e (y seV#ential representation Since a heap is a complete or nearly complete (inary tree, therefore a heap of siAe n is represented in memory #sing a linear array of siAe n.

## Bepresentation of heap in ,e,ory

Ceap 1 Beap +0 21 ,0 , 2 + , 0 1 ,0 +0 , 2, 20 21

2,

20

## "e-uential representation of ,a heap

Operation on heaps
Deletin: an ele,ent fro, the heap; Olement from the heap is always deleted from root of the heap. If we delete element from the root it create hole, vacant space , in root position 4eca#se heap m#st (e complete, we fill the hole with the last element of the heap.

## Deletin: an ele,ent fro, the heap

'ltho#gh heap (ecomes complete i.e satisfies shape property, the order property of heap is violated. 's the val#e come from the (ottom is small. *e have to do another operation to satisfy the order property. -his operation involves moving the element down from the root position #ntil either it ends #p in a position, where the root property is satisfied or it hits the leaf node. -his operation in text will (e referred as reheapify downward operation.

,0 +0 21 ,

2,

20

"tartin: heap

+0 21

2,

20

+0 , 21

2,

20

## Deletin: an ele,ent fro, the heap

BeheapifyDownward\$heap0start0finish% Bere heap is a linear array, start is the index of the element from where reheapify downward operation is to start, and finish is the index of last element of the heap. -he varia(le inde is #sed to keep track of index of the largest child. 9e:in if heap=start> is not leaf node then set index?index of the child with largest val#e if6heap=start>Wheap=index>8 than swap heap=start> and heap=index> call 3eheapifyCownward6heap,index,finish8 endif endif end

## Department of CSE and IT, JUIT Waknaghat

5oid reheapifyCownward6int heap=>,int start,int finish8 9 int index,lchild,rchild,maxim#m,temp< lchild?27start< Q7index of the left child7Q rchild?lchild;1< Q7index of the right child7Q if6lchildW?finish8 9 maxim#m?heap=lchild>< index?lchild< if6rchildW?finish8 9 if6heap=rchild>:maxim#m8 9 maxim#m?heap=rchild>< index?rchild< @ @ if6heap=startWheap=index>8 9 temp?heap=start>< heap=start>?heap=index>< heap=index>?temp< reheapifyCownward6heap,index,finish8 @ @ @

## -he deletion from the heap is done in following steps)

'ssign the val#e of the root to the temporary varia(le, which may (e reV#ired for f#rther processing. 4ring the last element of the heap to the root node position. 3ed#ce the siAe of the heap (y factor of one. 'pply reheapify downward operation from root node.

## Deletin: an ele,ent fro, the heap

Delete/le,et\$heap0n0ite,% Bere heap is the linear array with siAe n. this algorithm deletes the element from the root of heap and assign to item thro#gh which it is ret#rned to the calling program. 9e:in set item?heap=1> set heap=1>?heap=n> set n?n/1< Rall reheapifyCownward6heap,1,n8 /nd

## Deletin: an ele,ent fro, the heap

Int delementOlement6int heap=>,int 7n8 9 int temp< temp?heap=1>< heap=1>?heap=7n>< 67n8//< reheapifydownward6heap,1,n8< ret#rn temp< @

## 1nsertin: an ele,ent into heap

Olement is always inserted as the last children of the heap. 4y the insertion heap remains complete (inary tree, (#t order is violated. *e have to do another operation to move the element #p from the last position #ntil it either it ends #p in a position where the root property is satisfied or we hit the root node. -his operation in the text is referred as reheapify #pward operation.

,0 +0 21 ,

2,

20

"tartin: heap

,0 +0 21 , 20

2,

20

2dd =alue M6

,0 +0 21 20 ,

2,

20

20 +0 21 ,0 ,

2,

20

## 1nsertin: an ele,ent into heap

Beheapify(pward\$heap0start% Bere heap is a linear array, start is the index of the element from where reheapify#pward operation is to start. It #se parent as the index of the parent node in the heap. 9e:in if heap=start> is not root node then if6heap=parent>Wheap=start>8 then swap heap=parent> and heap=start> call 3eheapify%pward6heap,parent8 endif endif end

## !5K Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

Department of CSE and IT, JUIT Waknaghat 5oid reheapify%pward6int heap=>,int start8 9 int temp, parent< if6start:18 9 parent?startQ2< if6heap=parent>Wheap=start>8 9 temp?heap=start>< heap=start>?heap=parent>< heap=parent>?temp< reheapify%pward6heap,parent8 @ @ @

The insertion of an ele,ent into heap is done usin: the followin: steps;

Increase the siAe of the heap (y a factor of 1. Insert the element as the last element of the heap. 'pply reheapify #pward operation from the last node.

## 1nsertin: an ele,ent into heap

1nsert/le,ent\$heap0n0ite,% Bere heap is the linear array with siAe n. this algorithm inserts an elemet item into the heap and also increases the siAe (y a factor of 1. 9e:in set n?n;1 set heap=n>?item< call reheapify#pward6heap,n8 end

## 1nsertin: an ele,ent into heap

5oid insertelement6int heap=>,int 7n,int item8 9 67n8;;< heap=7n/1>?item< reheapify#pward6heap,7n/18< @

## Department of CSE and IT, JUIT Waknaghat

2pplications of Ceaps
1,ple,entin: a priority -ueue "ortin: an array usin: efficient techni-ue known as heap sort

Priority <ueues
-he priority V#e#e is a data str#ct#re in which the intrinsic ordering of the data items determines the res#lt of its (asic operation. -he priority V#e#e can (e classified in two types) 1.'ssending priority V#e#e 2.Cescending priority V#e#e

## Department of CSE and IT, JUIT Waknaghat

9uildin: a Ceap
4efore we can apply heap sort techniV#e for sorting an array, the first task is to (#ild a heap i.e. convert an #nsorted array into a heap.
1 2

+ , 0 1

10 , 10 1, 12 , ,0

10 , , 10 ,0

1,

12

4#ilding a heap
10 , , 10 ,0

1,

12

10

10

1,
2rray

12

,0

4#ilding a heap
10 1, , 10 ,0

12

10

1,

10

,
2rray

12

,0

4#ilding a heap
10 1, , ,0 10

12

10

1,

,0

,
2rray

12

10

## Department of CSE and IT, JUIT Waknaghat

4#ild Beap
Ceapify\$a0n% Bere a is the linear array with siAe n. this algorithm (#ilds max. heap 4egin set index?parent of the node with index n for i?index to 1 (y /1 do call reheapify #pward6a,i,n8 endfor Ond

4#ild Beap
5oid heapify6int a=>, int n8 9 int i,index< index?nQ2< for6i?index<i:?1<i//8< reheapify%pward6a,i,n8< @

## Department of CSE and IT, JUIT Waknaghat

Ceap "ort
Neneral approach of heap sort; 1. From the given array (#ild the initial max heap. 2. Interchange the root 6maxim#m8 element with the last element. . %se reheapify downward operation from the root node to re(#ild the heap of the siAe one less then the starting. +. 3epeat steps 1 and 2 #ntil there are no more elements.

example
Initial elements are) 10, ,, 10, 1,, 12, ,, ,0 'fter heapify operation)
1 2 + , 0 1

10

1,

,0

12

10

## Department of CSE and IT, JUIT Waknaghat

Swap reheapifyCownward Swap reheapifyCownward Swap reheapifyCownward Swap reheapifyCownward Swap reheapifyCownward Swap Final sorted array

10 ,0 10 , 12 1, , 12 10 10 , ,

1, 1, 1, 1, 1, 12 12 , , , 10 10

,0 , , 10 10 10 10 10 12 12 12 12

, , , , , , 1, 1, 1, 1, 1, 1,

12 12 12 12 , , , , , , , ,

, 10 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0

10 10 10 10 10 10 10 10 10 10 10 10

Beap sort
Ceapsort\$a0n% Bere a is the linear array of siAe n in memory. -his algorithm sorts this array in ascending order #sing heap sort method. 4egin call heapify6a,n8 for i?n to 2 (y /1 do interchange elements a=1> and a=i> call reheapifydownward6a,1,i/18 endfor end

## Department of CSE and IT, JUIT Waknaghat

Beap sort
5oid heapsort6int a=>,int n8 9 int i,temp< heapify6a,n8< for6i?n<i:1<i//8 9 temp?a=1>< a=1>?a=i>< a=i>?temp< reheapifydownward6a,1,i/18< @ @

STUDENT T S?S"
1. Write a com"lete c "rogram to create 5a7. Kea" of the following sequence 32 02 &2 *2 132 1@2 12 52 02 11 2. Write a function to delete an item at inde7 i from Kea". 3. Write a c "rogram to sort the following sequence b\$ using hea" sort. 1@2 52 0@2 152 122 352 5@

Practical No.1A
_______________________________________________________________________ _ I!" Getting acquainted with Graphs.

#\$JECTI%E
The goal of this lab is to help you become acquainted with how to Graphs and various operations on graphs li>e 9Q& and &Q& etc. !:H Data Structures Team: Dr. Nitin, Dr.Yashwant, Dr.Ravi

## Department of CSE and IT, JUIT Waknaghat

Nraphs
ObKecti=es; Cescri(e a graph Cescri(e how graph can (e represented in memory Implements the vario#s operations on graphs Cescri(e applications of graphs

1ntroduction
Uraph is another important non linear data str#ct#re. -his data str#ct#re is #sed to represent relationship (etween pairs of elements, which are not necessarily hierarchical in nat#re. ' graph is defined as) FUraph U is a ordered set 65,O8, where 56U8 represent the set of elements, called vertices, and O6U8 represents the edges (etween these vertices.I Uraphs can (e
N %ndirected N Cirected

## Department of CSE and IT, JUIT Waknaghat

Nraphs
Fig#re shows a sample graph 56U8?9v1,v2,v ,v+,v,@ O6U8?9e1,e2,e ,e+,e,@
e2 v1 v, e e, v+

e1

v2

e+

Nraph
e2 v1 v, e e, v+

e1

v2

e+

## Li:? \$b% Directed Nraph

In directed graph, an edge is represented (y an ordered pair 6#,v8 6i.e.?6#,v88, that can (e traversed only from # toward v.

## Department of CSE and IT, JUIT Waknaghat

Nraph Ter,inolo:y
2dKacent #ertices; 's an edge e is represented (y pairs of vertices denoted (y =#,v>. -he vertices # and v are called endpoints of e. these vertices are also called adJacent vertices or neigh(ors. De:ree of a =erte ) -he degree of vertex #, written as deg6#8, is the n#m(er of edges containing #. If deg6#8?0, this means that vertex # does not (elong to any edge, then vertex # is called an isolated vertex.

Nraph Ter,inolo:y
Path; ' path & of length n from a vertex # to vertex v is defined as seV#ence of 6n;18 vertices i.e. &?6v1,v2,v ,HHvn;18 S#ch that #?v1, v?vn;1 -he path is said to (e closed if the endpoints of the path are same i.e. v1?vn;1. -he path is said to (e simple if all the vertices in te seV#ence are distinct, with the exception that v1?vn;1.In that case it is known as closed simple path.

## Department of CSE and IT, JUIT Waknaghat

Nraph Ter,inolo:y
Cycle; ' cycle is closed simple path with length two or more. Sometimes, a cycle of length k 6i.e. k distinct vertices in the path8 is known as k/cycle. Connected Nraph; ' graph is said to (e connected if there is path (etween any two of its vertices, i.e. there is no isolated vertex. 2 connected :raph without any cycles is called a tree? Thus we can say that tree is a special :raph?

Nraph Ter,inolo:y
Co,plete Nraph; ' graph U is said to (e complete or f#lly connected if there is a path from every vertex to every other vertex. ' complete graph with n vertices will have n6n/18Q2 edges.

## Department of CSE and IT, JUIT Waknaghat

Nraph Ter,inolo:y
Oei:hted Nraph; ' graph is said to (e weighted graph if every edge in the graph is assigned some data. -he weight is denoted (y w6e8. w6e8 is non negative val#e that may (e representing the cost of moving along that edge or distance (etween the vertices.
2 0 1 1 + , + 2 2 ,

2 + 0

## Oei:hted undirected :raph

Nraph Ter,inolo:y
+ultiple /d:es; Cistinct edges e and eD are called m#ltiple edges if they connect the same end points i.e., if e?=#,v> and eD?=#,v> +ulti:raph; ' graph containing m#ltiple edges. \$oop) 'n edge is a loop if it has identical endpoints, i.e. if e?=#,#>

## Ter,s rele=ance with directed :raph only

Directed Nraph; ' directed graph U is graph in which each edge is assigned a certain direction, i.e. each edge is ordered pair of 6#,v8 of vertices rather than an #nordered pair =#,v> S#ppose U is a directed graph with e?6#,v8 as one of the edge, then e (egins at # and ends at v. # is the origin of e, and v is the destination of e # is predecessor of v, and v is the s#ccessor of #.

## Directed Nraph ter,inolo:y

Out de:ree and 1n de:ree of a =erte ; -he o#t/degree of vertex #, denoted (y o#tdeg6#8, is the n#m(er of edges originating at #. -he in/degree of a vertex #, denoted (y indeg6#8, is the n#m(er of edges terminating at #.

## Directed Nraph ter,inolo:y

"ource and sink; ' vertex # is called a so#rce if it has a o#t/ degree greater than Aero, (#t Aero in/ degree. ' vertex # is called a sink if it has a in/ degree greater than Aero, (#t Aero o#t/ degree.

## Directed Nraph ter,inolo:y

Beachability; 5ertex v is said to (e reacha(le from # if there exists a path from vertex # to vertex v. "tron:ly Connected; ' directed graph U is said to (e strongly connected, if for each pair #, v of the vertices in U, if there exists a path from # to v, there m#st exist path from v to #< otherwise the directed graph is #nilaterally connected.

## Directed Nraph ter,inolo:y

Parallel /d:es; Cistinct edges e and eD are called parallel edges if they connect the same so#rce and terminal vertices, i.e.if e?6#,v8 and eD?6#,v8 "i,ple Directed Nraph; ' directed graph U is said to (e simple, if there are no parallel edges. ' simple directed graph may have loops, (#t it can not have more than one loop a a given vertex. Directed cyclic Nraph; ' directed cyclic graph U is a graph witho#t cycle6s8.

Bepresentation of Nraph

## 2dKacency +atri Bepresentation

Ronsider a directed graph U?65,O8. *e will ass#me that the vertices are n#m(ered 1,2, ,..\v\, in some ar(itrary manner. -he adJacency matrix representation of a graph U then consists of \v\ ! \v\ matrix '?6aiJ8, s#ch that aiJ? 1 if 6I,J8] O 0 otherwise

## 2dKacency +atri Bepresentation

For #ndirected graph U?65,O8, the adJacency matrix representation is also consists of \v\!\v\ matrix '?6aiJ8 (#t its elements are as follows) aiJ? 1 if either =I,J> ] O or =J,i> ] O 0 otherwise

## 2dKacency +atri Bepresentation

1 0 1 0 0 1 2 1 0 1 0 1 + , 0 0 1 1 0 1 0 0 0 0 0 1 0 1 0

1 2 + ,

## 2dKacency +atri Bepresentation

1 0 0 0 0 1 2 1 0 1 1 0 + , 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0

1 2 + ,

## 2dKacency +atri Bepresentation

'dJacency matrix for non weighted graphs that contains entries of only 0 and 1 is called (it matrix or a 4oolean matrix. 'dJacency matrix representation of a graph reV#ires 06v28 memory location irrespective of their n#m(er of edges in the graph.

## 2dKacency List Bepresentation

-he 'dJacency \$ist 3epresentation of a graph U?65,O8 consists of an array 'dJ of \5\ lists, one for each vertex in 5. For each # ] 5 , the adJacency list 'dJ=#> contains all the vertices v s#ch that there is an edge 6#,v8 ] O i.e. 'dJ=#> consists of all the vertices adJacent to # in U. -he vertices in each adJacency list are stored in an ar(itrary order.

## 2dKacency List Bepresentation

If U is an #ndirected graph, the s#m of the lengths of all the adJacency lists 2\O\. If U is an directed graph, the s#m of the lengths of all the adJacency lists \O\. 'ltho#gh the adJacency list representation reV#ires very less memory as compared to the adJacency matrix. -he simplicity adJacency matrix make it prefera(le when graphs are reasona(ly small.

1 2

2 1 2 x x

, ,

x x

+ ,

, 2

1 2

2 , 2

x x x x + 1 x

+ ,

## 1,ple,entation of 2dKacency list in C

Lor non wei:hted :raph; ^define L'! ,0 -ypedef str#ct nodetype 9 int vertex< str#ct nodetype 7next< @graphnode< graphnode 7adJ=L'!>< Lor wei:hted :raph; -ypedef str#ct nodetype1 9 int vertex< int weight< str#ct nodetype1 7next< @graphnode1< graphnode1 7adJ=L'!><

## Department of CSE and IT, JUIT Waknaghat

Operations on Nraphs
Creatin: an e,pty :raph; -o create an empty graph, the entire adJacency list is set to "%\$\$. 5oid creatgraph6graphnode 7adJ=>, int n#m8 9 int i< for6i?1<iW?n#m<i;;8 adJ=i>?"%\$\$< @ 5oid creatweightedgraph6graphnode1 7adJ=>, int n#m8 9 int i< for6i?1<iW?n#m<i;;8 adJ=i>?"%\$\$< @
/nterin: Nraph infor,ation; -he graph information is entered as shownH 5oid inp#tgraph6graphnode 7adJ=>, int n#m8 9 graphnode 7ptr,7last< int I,J,m,val< for6i?1<iW?n#m<i;;8 9 last?"%\$\$< printf6FGno. of nodes in the adJacency list of node PdI,i8< scanf6FPdI,Ym8< for6J?1<JW?m<J;;8 9 printf6Fenter nodePd)I,J8< scanf6FPdI,Yval8< ptr?6graphnode78malloc6siAeof6graphnode88< ptr/:vertex?val< ptr/:next?"%\$\$< if6adJ=i>??"%\$\$8 adJ=i>?last?ptr< else 9 last/:next?ptr< last?ptr< @ @ @ @

## Department of CSE and IT, JUIT Waknaghat

/nterin: Nraph infor,ation; -he graph information is entered as shownH 5oid inp#tweightedgraph6graphnode1 7adJ=>, int n#m8 9 graphnode1 7ptr,7last< int I,J,m,val,wt< for6i?1<iW?n#m<i;;8 9 last?"%\$\$< printf6FGno. of nodes in the adJacency list of node PdI,i8< scanf6FPdI,Ym8< for6J?1<JW?m<J;;8 9 printf6Fenter nodePd)I,J8< scanf6FPdI,Yval8< printf6Fenter weight for edge PdPd)I,I,val8< scanf6FPdI,Ywt8< ptr?6graphnode78malloc6siAeof6graphnode88< ptr/:vertex?val< ptr/:weight?wt< ptr/:next?"%\$\$< if6adJ=i>??"%\$\$8 adJ=i>?last?ptr< else 9 last/:next?ptr< last?ptr< @ @ @ @

Operations on Nraphs
Outputtin: a Nraph; 5oid printgraph6graphnode 7adJ=>,int n#m8 9 graphnode 7ptr< int I< for6i?1<iW?n#m<i;;8 9 ptr?adJ=i>< printf6FPdI,i8< while6ptrZ?"%\$\$8 9 printf6F/:PdI,ptr/:vertex8< ptr?ptr/:next< @ printf6FGnI8< @ @

## Department of CSE and IT, JUIT Waknaghat

Operations on Nraphs
Outputtin: a Nraph; 5oid printweightedgraph6graphnode1 7adJ=>, int n#m8 9 graphnode1 7ptr< int I< for6i?1<iW?n#m<i;;8 9 ptr?adJ=i>< printf6FPdI,i8< while6ptrZ?"%\$\$8 9 printf6F/:Pd,PdI,ptr/:vertex,ptr/:weight8< ptr?ptr/:next< @ printf6FGnI8< @ @

Operations on Nraphs
Deletin: a Nraph; 5oid deletegraph6graphnode 7adJ=>, int n8 9 int I< graphnaode 7temp,7ptr< for6i?1<iW?n<i;;8 9 ptr?adJ=i>< while6ptrZ?"%\$\$8 9 temp?ptr< ptr?ptr/:next< free6temp8< @ adJ=i>?"%\$\$< @ @

## Department of CSE and IT, JUIT Waknaghat

Operations on Nraphs
Deletin: a Nraph; 5oid deleteweightedgraph6graphnode1 7adJ=>, int n8 9 int I< graphnaode1 7temp,7ptr< for6i?1<iW?n<i;;8 9 ptr?adJ=i>< while6ptrZ?"%\$\$8 9 temp?ptr< ptr?ptr/:next< free6temp8< @ adJ=i>?"%\$\$< @ @

Tra=ersal
Lany applications of the graphs reV#ires examining the vertices and edges of a graph U. there are two standard ways for graph traversal) 9readth first search Depth first search

## Department of CSE and IT, JUIT Waknaghat

Uiven an inp#t graph U?65,O8 and so#rce vertex s, from where to (egin. -he 4FS systematically explores the edges of U to discover every vertex that is reacha(le from s. It prod#ces a (readth first tree with root s that contains all s#ch vertices that are reacha(le from s. For every vertex v reacha(le from s, the path in the (readth first tree from s to v corresponds to a shortest path.

C#ring the exec#tion of the algorithm, each node n of U will (e one of the three states, called the stat#s of n as follows) Stat#s?1) 6ready state8 the initial state of the node n Stat#s?2) 6waiting state8 the node n is on the V#e#e or stack waiting to (e processed. Stat#s? ) 6processed state8 the node has (een processed.

Oxample

(ndirected Nraph

## 2dKacency List Bepresentation

1 2

+ 1 2

2 , , 2 2

x + 0 , 0 x x x x x

+ , 0

1 + ,

## Department of CSE and IT, JUIT Waknaghat

'lgorithm
Step 1)InitialiAe all nodes to ready state 6stat#s ?18 Step 2) &#t the starting node in V#e#e and change its stat#s to the waiting state 6stat#s?28 Step ) 3epeat step + and , #ntil V#e#e is empty Step +) 3emove the front node n of V#e#e. &rocess n and change the stat#s of n to the processed state 6stat#s? 8 Step ,) 'dd to the rear of the V#e#e all the neigh(or of n that are in ready state 6stat#s?18, and change their stat#s to the waiting state 6stat#s?28 =end of the step loop> Step 0) exit

4FS
Step 1) Initially add 2 to the V#e#e
F?0 3?0 F 2 3

Step 2)remove the front element 2 from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of 2
F?1 3?+ F 2 1 , + 3

## Department of CSE and IT, JUIT Waknaghat

4FS
Step )3emove the front element 1 from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of 1
F?2 3?+ F 2 1 , + 3

Step +)3emove the front element , from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of ,
F? 3?, F 2 1 , + 0 3

4FS
Step ,) +)3emove the front element + from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of +
F?+ 3?, F 2 1 , + 0 3

Step 0)3emove the front element 0 from V#e#e (y setting front?front ;1 add to the V#e#e the neigh(ors of 0
F?, 3?, F 2 1 , + 0 3

## Depth Lirst "earch

-he CFS, as the name implies, is to search deeper in the graph, whenever possi(le. -he edges are explored o#t of the most recently discovered vertex v that still has #nexplored edges leaving it. *hen all of vDs edges have (een explored, the search (acktracks to explore edges leaving the vertex from which v was discovered. -his process contin#e #ntil we have discovered all the vertices that are reacha(le from the so#rce vertex. CFS #ses stack to maintain the order in which the vertices are to (e processed.

'lgorithm
Step 1)InitialiAe all nodes to ready state 6stat#s ?18 Step 2) &#sh the starting node in stack and change its stat#s to the waiting state 6stat#s?28 Step ) 3epeat step + and , #ntil stack is empty Step +) pop the top node n of stack. &rocess n and change the stat#s of n to the processed state 6stat#s? 8 Step ,) &#sh on to stack all the neigh(or of n that are in ready state 6stat#s?18, and change their stat#s to the waiting state 6stat#s?28 =end of the step loop> Step 0) exit

## Department of CSE and IT, JUIT Waknaghat

CFS
Step1) Initially, p#sh on to the stack as follows) stack) Step2) pop and print the top element and p#sh onto the stack all the neigh(ors of 6 those are in the ready state8 as follows) print) stack) 2, ,, 0 Step ) pop and print the top element 0 and p#sh onto the stack all the neigh(ors of 0 6 those are in the ready state8 as follows) print)0 stack) 2, ,

CFS
Step+) pop and print the top element , and p#sh onto the stack all the neigh(ors of , 6 those are in the ready state8 as follows) print), stack) 2,+ Step,) pop and print the top element + and p#sh onto the stack all the neigh(ors of + 6 those are in the ready state8 as follows) print)+ stack) 2, 1

## Department of CSE and IT, JUIT Waknaghat

CFS
Step0) pop and print the top element 1 and p#sh onto the stack all the neigh(ors of 1 6 those are in the ready state8 as follows) print)1 stack) 2 Step1) pop and print the top element 2 and p#sh onto the stack all the neigh(ors of 2 6 those are in the ready state8 as follows) print)2 stack) "ow the seV#ence is ,0,,,+,1,2

STUDENT T S?S"
1. Write a menu driven "rogram to im"lement following o"erations on gra"h: i. .reation of a gra"h using ad<acenc\$ list+ad<acenc\$ 5atri7 ii. !ddition and deletion of a nodes iii. 4raversing 1. CF= 2. /F= A