0% found this document useful (0 votes)
27 views48 pages

Data Structures Lab Programs

these are lab programs of bca 1st sem under bangalore university

Uploaded by

7neelusingh14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
27 views48 pages

Data Structures Lab Programs

these are lab programs of bca 1st sem under bangalore university

Uploaded by

7neelusingh14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 48
Data Structure Using © I Write a program to push 5,0,34,17) display the popped numbers Ans. Refer Chapter 6, Program No. 6.1 Ans, Refer .tapter 6, Program No. 6.6 EBFE ice « program to inert the olements (6,7 SaREEE from it(using linked list implementation). Ans. Refer Chapter 7, Program No. 7.4 to create rt 45 and 1 Ex Dota Structure Using © Suppose our search space is exhausted after k steps, Then, O(log, n). Time Complexity in the average case is almost approximately the worst case, 3 The time complexity of binary search ina successful search is O(log, n) and for is O(log, n). 5 #include #include int A[2e8], n, key; /* Include Isearch() code from Example 10.1 */ /* Include binsearch() code from Example 10.2 */ void acceptInput() { int 4; printf ("Enter Number of Elements : scanf ("Kd", &n); for (i = @:i¢ nj ist) i printf ("Enter Element ‘di scant ("%d",8A[4})5 } printf ("Enter an Ele scanf ("%d" key); } void main( printf(*\n 3, txt"); printf("\n Enter your choice scanf("Rd", ch) 5 switeh(eh) { case 1: acceptinput()s flagelsearch(A,n, key) Af (Mage=-1) printf(*\n Search 45 Unsuccessful."); ws printf(*\n An Element %d Found at Position : breaks print#("\n Enter Elements in Ascending Order for Binary Search\n"); ‘accept Input ()i fag = binsearch(A,n, key); if (fagse-2) printf("%d not found in array \n"» Key) else _ printf ("An Element 4d Found at Position : ‘Xd \n", key, flag); break; ~ ene case 3: exit(@)s case 2: 1, Linear Search 2. Binary Search 3. bt Enter your choice 1 1 Enter Nunber of 1 Enter Element 1:4 Enter Element fnter Element: 3; Bon elements to be SOF ted. for pean oleate for jo ton pass = 2 watil>alt 1) then tomp = 2 (3) atsa td a (44a) = temp end for ‘The complete C1 program ram to sort n nu numbers usin} int pass, temp, 33 for (pass = 13 pass _n(nt] 2 Which is of O(n*). #includecstdio.h> #includecstdlib.h> Structure Using © void insertion sort (int a[], int n) { Ant pass, K, temp, $3 for (pass = 1; pass < nj passt+) ali +2) = ais ali +i) =k; /* inserting } } void acceptinput() { Seorhing ond Sorng EEE accept input()) for(ke®} keen; kee) r Locemax(a,ksn); /* find the largest element location */ tempeatk}} a{k}=a[ loc}; a[1oc]=tenp; ) display(); break; case 3: exit(0); [Output : Sorting Techniques | Sorting Techniques 1, Insertion Sort 1. Insertion Sort 2. Selection Sort 2. Selection Sort | Enter your choice : 1 Enter your choice : 2 | Enter the number of elements : 8 Enter the number of elenents : 8 Enter the array elements : 75 8 116 48 3.70 | Enter the array elenents : 75 8 1 16 48 37 @ The Sorted Array is: 75 4@ 16 8 7 3 1 0| The Sorted Array is: 75 48 16 8 7 3 1 @ Searching refers to finding foran item in any list. Itis one of the common operations in data processing. Searching an employee details from the employee database or searching a telephone number from the telephone directory are few of the daily life instances. Searching should be efficient and quick as the list may be large and large amount of data has to be processed. In this chapter we deal with different searching techniques and their advantages and disadvantages. The programmer has to select the best technique to the given problem. Searching is made easy when the list is sorted. Based on the efficiencies with which a search is to be made, different searching techniques are involved. The frequently used searching techniques are: (1) Sequential search / linear search. (2) Searching an ordered table. (3) Indexed sequential search, (4) Binary search. (5) Interpolation search. letus discuss Linear and Binary search techniques in detail in the following sections. . - ipinclude etudecstb > struct node int INFO; struct node *LINKs » typedef struct node NODE; ove *start=NULL} J> include create() code from example 5.4 */ /? Include display() code from example 5.7 */ Jr include length() code from example 5.8 */ jr Include Insert_beg() code fron example 5.10 */ Jr Include insert_end() code fron example 5.11 */ {* Include insert_pos() code from example 5.12 +/ Jf Include delete beg() code from example §.13 */ /f Include delete_end() code from example 5.14 +/ JP Include delete _pos() code from example 5.15 */ J* Include delete item() code fron exanple 5.16 */ ‘void main() { int ch, item, pos; while(1) printf("\n 1. Create 2 Linked List "); printf("\n 2. Display *); Printf("\n 3. Insert First Node )s _-printf("\n 4. Insert at the End *); printf("\n 5. insent at the Specified Position“); int e inst Node"); BEEK os trees sie f cose 2: printf(*\n Enter the Item to fi | seonetnst, HLean)y | printf(*\n Linked List before tns display()i insert_beg(item); printfc*\n Linked List a display() breaks printé("\n Enter th scanf("%d", Site) printf(*\n Linked List be printf ("\n break: printf("\n Linked List after Deletion f# § \n")y aisplay()s break printf(*\n Linked List before Deletion is < \n*)y display(); delete_end(); printf("\n Linked List after Deletion is : \n"); aisplay(); break; printf("\n Enter a Valid Position to Delete : \n” scanf("Kd",8p0s); 4F((pos==@)||| (pos>length())) { print#("\n It is Invalid position \n"); breaks } else £ print®("\n display(); delete_pos(pos); | Enter a Valid Position cifed Position eat the Specified Position 3 Node When Ites is Given Your Chatce £1 he node 1 262 Do you wish to add one more node (Y/N) 1 Enter the node 2 316 do you wish to add one more node (Y/N) = ¥ Enter the node 3 38 Do you wish to add one more mode (Y/N) = Enter the node 4 :27 Do you wish to add one more node (¥/N) Create a Linked List Display Insert First Node Linear Queue Implementation Using Arraya ma" eect reecst10.0> titine 10 nt QUEVELN] FRONT=0, REAR=-1, ITEM, yo snetude Ginsert() code from Example 7.1 +/ Jr include Qdelete() code fron Example 7.2 +/ Je include Qéisplay() code from Exanple 7.5 */ void main() { int chi while(2) { printf("\n Queue Inplementation using Array"); printf("\ntesrs+sessernasesscens, printf("\n 1. Insert into Queue "); printf("\n 2. Delete fron queue “); printf("\n 3. Display Queue *); printf("\n 4. Exit "); printf("\n Enter your choice : Sean (°%A" eh); switch ch) i case 1: Qinsert(); Qdisplay(); break; case 2: Qdelete(); Qdisplay( break; Qdisplay(); Date Structures: Enter your choice + Queue Inplenentation using Enter an Item : 16 theeteaiies seeenle | Queue: 61 16 1. Insert into Queue | front exenent of the Queue 4s = 63 2. Delete from Queue Rear Elenent of the Queue is : 16 Queue Inplenentation using Array 1. Insert into Queue 2, Delete fron Queue 3. Display Queue 4. exit Enter your choice Enter an Item : 8 queue: 61 16 8 Front Element of the Queue is : 61 Rear Elenent of the Queue is : 8 Queue Implementation using Array 2; Delete From Quel 4. Insert into Queue 2. Delete fron Queue 3. Display Queue 4, Exit Enter your choice : 1 Enter an Item : 27 Queue: 61 16 2 Front Element of the Queue is : 61 Rear Elenent of the Queue 1s : 27 Queue Implementation using Array eeeenes steeeeeteeeeenaney 1. Insert into Queve ¢ from Queue peu places 1. Insert into fae rrr your choic to insert an ITEM into a puncton (fiegansert ) : EARL) % N)) ae ((FRONT==CR of peiner("\n Queue Overfiow”); else printf("\n Enter the Element Scanf("\n A" ,BITEM) 5 if (FRONT==-4) FRONT=REAI else REAR=(REAR*1)2N5 (QUEUE[REAR]=ITEM; ) ) + function to display a11 the elem wid cQdisplay() printf(*\n No elements in else { printf(*\n Circular Queve AF(FRONT<=REAR) { for(isFRONT; ic=REAR;it+) pranee("\ tt, queue /*queue 1s initially enptyt/ a circular queue */ J* to check overflow condition */ to be Inserted:*); /* if queue is empty */ /* 4 queue 1s not eopty */ /* increment REAR position */ /* insert an ITEM at REAR position*/ rents in a circular queue */ /* if queue is enpty */ the CQueue”); Ds * Function to delete an ITEM from a circular queu void cQdelete( ) { Sf (FRONT==-1) printF("\n Queue Underfiow); else { TTEM=QUEUE[ FRONT] printf("\n The Deleted Item is AF (FRONT==REAR) FRONT-REAR=-13 else FRONT=(FRONT#1) 3 void main( ) { Ant ch; wnile(a) { Circular ‘queue implementation using Array ar queve Insert cireul | circular Queue Delete # Circular queue Display |. pat your choice Eeator queue = entrenent of the CQueue 4 + 61 Elenent of the CQueue is : 62 lar Queue implenentation using Array Insert Grcular Queue Delete Circular Queue Display exit a ‘the Element to be Inserted:16 r Queue : 61 16 262 é of the CQueue is : 16 sr Queue implementation using Array 2. Circular Queve Insert 2. Circular Queve Delete 3. Circular Queve Display 4, Exit Enter your Choice ; 2 ‘The Deleted Iten is ; 16 Circular Queue a 7 Front Element of the Cqueue is : & Rear Element of the CQueue is : 27 Circular Queue implementation using Array 2. Circular Queue Insert 2. Circular Queue Delete 3. Circular Queve Display 4. exit Enter your choice ; 2 The Deleted Iten is : 8 Circular Queue 7 Front Element of the CQueue is : 27 Rear Element of the CQueue is : 27 Circular Queue implementation using Array 2. Circular Queue Insert 2. Circular Queue Delete 3. Circular Queue Display 4. exit Enter your Choice staio.h> include sudecstolib-N> struct node int INFOS struct node *LINK) % : cypesef struct node NODE; nooe *starteNULls void insertordered(int data) { NODE *NEWNODE= (NODE *)malloc(sizeof(NODE)); NEMNODE->INFO = data; Af(startqsNULL) /* To create first node */ ‘ stant = NEWNODE; start-> LINK=NULL; } 4 ‘else if(data < start->INFO) /* If data 1s lesser than first node value */ TR = NULL 8& d : BEEK 20s tina a print f(*\n List 18 Empty") else if(data a= start: SINFO) ‘ starteCURRPTR free(PREVPTA)5 ) else ab ie in) i ant chy datas woite(1) { print#(7\n Ordered Linked List Operations"); printf("\n ** peint#("\n 1. Insert); print#("\n 2. Delete’); print#("\n 3. Display"); peint#("\n 4. Exit"); peintf("\n Enter Your choice scanf 7X4" Ech); switch(ch) { printf("\n Enter Data to be Inserted scanf("X4",8éata); printf("\n_ Linked List before Insertion is: display(); insertondered(data); printf("\n. Linked List after Insertion is: \n"); display(); breaks [venues gered Linked List Operat ons pelete Display exit enter Your Chote ¢ 2 Enter bata to be Taserted £61 Linked List before Insertion 18% empty Linked List after Tosertion 1st 61 > NULL ordered Linked List Operations: Enter Your Choice 7 1 Enter Data to be Inserted + 16 | 2 > NULL. Linked List after Insertion is: 36 > 61 -> NULL F 1. Insert. 2, delete 3. Display 4. exit Linked List 16 => 61 => rite a ogra 0 ad WO ‘ineludecstdio.h> Aincludecstlib.hy struct polynontal int coeff; int power} struct polynomial *LINK} aH ‘typedef struct polynomial NOD! NODE ‘polyi=NULL, *poly2 = NULL, *poly3) = NULL NODE *create_poly(); NODE *add_poly(NODE *poly1,NODE *poly2); void display_poly(NODE ptr); _ /n To create the pelynoneloy vooe create poly { ant tes ant cee po Linton Late Jrroop while both of the linked lists have value while(polyt && poly2) { Af (poly1->power > poly2=spower) ( ‘emp_node->power = poly1-spower; tnp_node->coeff = polyi-»coeff} poly = poly->LINK; else if (poly1->power < poly2-rpower) ( ‘tmp_node->power = poly2->powe! tmp_node-rcoeff = poly2->coef poly2 = poly2->Lank; else { ‘tmp_node->power = poly1->power; ‘tmp_node->coeff = polyi->coeff + poly2->coeff; poly1 = poly1->LINk; poly2 = poly2->LINK; + if (poly && poly2) { ‘tmp_node->LINK = (NODE *) malloc(sizeof (NODE) ‘tmpinode = tmp_node->LINk; ‘tmp_node->LINK = NULL; ) y 7/Loop while either of the linked 1ict< haz value while(poly1 || poly2) { ‘tmp_node->LINK = (NODE +) malloc(sizeof(NODE)); ‘tmp_node = tmp_node->LINK; ‘tmplnode->LINK = NULL; if (poly1) { ‘tmp_node->power = poly1->power; _ tnponode- >coeff = polyi->coetF; | = poly1->LINK; prante(*\ncreate polytecreate poly()3 printé(n\n The First P% splay poly(Polyi)s poly2ecreate poly()i peinte("\n The Second Polynomial Expression 18:\N°); aisplay_poly(poly2) + ‘add poly(polyl, poly2)i printf("\n The Addition of Two Polynomials $5:\n")5 ‘define MAXSTK 5 int To int S[MAXSTK]; main() { int choice; while(1) ye renction to push an item onto the stack*/ vom) ee J ‘Stent 4 * As the ‘ en item to be pushed */ | print€("Stack Overfiow\n"); else print¢("Enter the item to be pushed in stack scant ("KS", Bites); ToPATOP+2; ‘S{ToP] = ites; ‘* Fuoction to pop an item from the stack */ 0 | 4¢(T0P == -1) -print€("Stack Underflow\n"); 1 o De pushed Hm stack your chatce 22 ne ites to De pushed im stack $9 aush Xe wit your chatce : 2 the ites to be pushed in stack © gram to Find GCD of three numbers = Enter Three Numbers : 468 Ged (46 8) =2 ‘The value being deleted {s HS", ptr -> info), Kd", ptr -> info); rr => Link; os Infix to Postfix /* Function to Push Character */ void push(char elem) i +4top; s[top]=elem; i * Output zi a Pe tinctien tor poping cherecter +) = int pop() Program to Convert infix to Posthix Expression { n teremaneneraneransmenanmanarmanaienatatud |} ak ay Enter the infix expression \| caer) xoy/(St2)42 | stop; retumn(elem); Postfix Expression conversion is xyasz*/2+ PrAnteCAMAEEPrOGTAN Co Evaluate Post printé("\n\t\t sthix Expres peintFC*\N Enter the posthy expr nf(°RS™, SposthX) ; seal for(i=85 ixstrlen(postix) ;i++) | { cchepostfx[i]} a(isdigit(ch)) rac peck whether digit * push(ch-"0"); ther digit */ else { ‘op2=pop()s ‘opi=pop()s switch(ch) { Eocomeegmemmres = 0014 o?2) Teel case ‘~' : res = opl - op2; break; res = opi * op2; breaks ‘opt / 0p2; breaks | pow(opi,0p2); breaks case case “/' = res case “N= Tes | prea reeae (pcre Gaamvelidcoaracters\U) | ) | | puntre) | } printf("Result of abov fe expression 15 + Xd \07,P200)3 program to Evaluate Posths expression session push(int element) /* Push operation */ Enter the postfix exPrs 53402 k Result of above expression 18:48 J int pop() 7+ Pop operation */ ( int elewent; elenent=s{top]3 ~-topi return(elenent); Program (o Create Binary Search ig Linked List a Tree and Perform Insert and Delete Ope pnerudecstaiont? anenudecstalid: struct node int infos struct node *lefts struct node *rights K oI pedef struct rode NODES none *root=NULL jp anctude disp() code fron exanple 8.2 */ jtnelude create() code fron example 8.6 */ Jp anorder successor in BST will be the mininun key in right subtree */ pope *getinsuccessor(NODE ‘ptr) { hile(ptr-pleft t= NULL) ptr = ptroleft; //this will give the mirinun key return ptr } NODE * deletion(NODE *p, int item) ( Nove *temp; 4f(Ip) ‘ printf(*Unable to delete. No such key exists.\n"); return 3 ) else if(iten > p->info) p-oright = deletion(p->right, item); ‘else if(iten < p->info) poleft = deletion(p-rleft, iten); 7 executing else means got the key Sf: else { 7* node has one child or no child if(p>iefe == NULL){ ‘temp = p->right; free(p); return teap; ee ei With inorder sucesso \n Enter the Number of Nodes : (*\n Enter the data for the node aitem); jodes are :\n\n\n\n")} ert ne choi ’ jes % umber of Nodes :7 1e data for data for 3 Jer the choice Tree nodes are re Binary se a 42 30. 8 7 45 Enter the choice : 1 Enter the Number of Nodes fnter the data for the node : 45 | Enter the data for the node : 19 Enter the choice : 3 The Binary Tree nodes are a :, % ss . 2 a [eee 45 18 w7 45 Enter the choice : 2 Enter an Item to be deleted 50 40 38 18 v7 Enter the choice : 2 Enter an Iten to be deleted se 40. 30 18 Enter the choice : 2 Enter an Item to be deleted : 50 40 30 18 a 19 wv 45 an 19 a1 45 19. traversals lib. | gincludecs' spe | setruct node “rights 2 et tac ade NDE ore oom eee eee ela ec ese nlcomnie ee void main() ‘ int item, ch msi; vile(1) { print#("\n Binary Search Tree Menu"); print#("\ eee print#("\n 1. Create "); printf("\n 2. Display ”); print#("\n 3. Preorder"); | print#(*\n 4. Inorder *); print#("\n 5. Postorder "); print#("\n 6. Exit "); printf("\n Enter the choice : 7); Bch); switch(ch) { ase 1: printf("\n Enter the Nunber of Nodes seanf("%4",8n); For(i=0;icn;ite) { printf(*\n Enter the data for the node ‘canf("X4", item); create(iten); ) ew a program to Create Binary Search Tree and perform inorder, preorder and postordler case 3 case 4 case $: case 6 print€(*\n The Binary Tree nodes aisp(root, 1); break; printf("\n Preorder traversal is pre_order(root); break; printf("\n Inorder traversal is in_order(root); break; printf("\n Postorder traversal is post_order (root) ; break; exit(a); Create Display Preorder Inorder Postorder eat the the the the the the the the the choice : 1) Number of Nodes data for the data for the data for the data for the data for the data for the data for the node node Search Tree Menu Display Preorder Tnorder Postorder Exit nter the choice ; 2 5 6 e The Binary Tree nodes are : 9 v7 node : node : node : node : node : Binary Search Tree Menu Create Display Preorder Inorder Postorder exit inter the choice 1 2 3 4. 5 6 o 3 Preorder traversal is Binary Search Tree Menu 2105 3 Create Display Preorder Tnorder . Postorder Exit Enter the choice 4 Inorder traversal is Binary Search Tree Menu @12 34 Create Display Preorder Inorder Postorder Exit Enter the choice anueune 5 Postorder traversal is: @ 1 3 6 9 Root 13 is moved to Afi)» j, locat te ee Al ACO) Att} ajay [ts Pots Root 08 is moved to A[O}" loca location, & swe? ACH AI AL) Atay a (41 08 | 13 | >. Als) a eee ys ; Sorted Arra Now let us see the algorithm for ¢or Constructing ing the h Program to Sort ‘n! Numbe: Un! Numbers using Heap So include - void heapify(int arr{], int n, int i) { J] Find largest among root, left child and right chitd int largest = i; int left = 2* i+; int right = 2* i +2; int temp; if (left arr[largest]) largest = left; if (right arr[largest]) largest = right; // swap and continue heapifying if root is not largest ) if (largest { tempzarr[i]3 arn[iJ-arr[largest]; arr{largest]=temp; heapify(arr, n, largest); } ) Void heapsort(int arr{], int ") ek // Build max heap int i, temp; for (i 2-1; 1 >= % // Heap sort for (i= n= 2; 4 >= 0; 4--) { tempearr[0]; arr[o}earr[is arr[i}=temp; // Meapify root elenent to get highest element at root again heapify(arr, 1, 0); int main() int arr[20]; int n 445 printf("Enter the size of the array : “); scanf("%4" ,&n); printf("\nenter the elements : *); for(i: scanf("%d" ,&arr[i]); heapSort (arr, n); printf("Sorted array is : for (i= 8; 1 cn; +h) printf("%d ", arr[i])s sicnsite) } Output: Enter the size of the array : 8 Enter the elements : 50 80 60 20 10 40 30 70 Sorted array is : 10 20 30 40 5@ 60 70 80 Eebipeectee ont ee eer ts The term trie has been taken from the word ‘retrieval’. A trie is an ordered tree data. was introduced in the 1960s by Edward Fredkin, All the search trees are used to. of numerical values but they are not suitable for storing the collection of words data structure which is used to store the collection of strings and makes seal words more easy. The term trie came from the word retrieval, Trie data struct a string from the collection of strings more easily. Trie is also called as Prefix Digital Tree. ‘The reason it is used to store String is that it has fast retrieval time, The comp ina Trie is 0(m), where mis the length of the string, Ifwe have stored a mill need to find a particular string, let's say cat then its complexity will be 0(3) and $2 II], Extract the substring “low” Find “are” in $2 and replace it with _— | #includecstdio.h> | #include een eae Find the length of S1 Il. Concatenate § int LENGTH(char *str) { int 1-0; while(str[i] !='\e") i; return i; } ST EmeNThar #582 chor "str int 4-0, 3-05 whize(stra[i}!="\0") at white (str2(j] Co) stra[il=str2(3]5 iss He > J= append *\e* to the end of first string */ strafi]="\e'5 SUBSTR(char str[],int pos,int len) char sub[5@]; int slen=LENGTH(str) ; “int p,Jomax_ext; "if (pos > slen ) printf »; return; ext = slen-postl; if (len > max ext) printf(“\n Invalid Substring Length "); pos - 15 yy 5 < ten ; 3+) sub[j] = strip] i] = "2's F("\n Substring = %5°, Sub); (char str[],char substr[],char replacestr{]) lar output[5®] 5 i= 0, j= 0, flag = 0, start = 0 check whether substring present in 2 string or rot */ (str[i] != "\e") (str[i] == substr{3]) sostr{50], repstr[5e], Sultch(ch) { case 1: case 2: case 3: printf("\n Enter the String : "); gets(stri); printf("\n The length of a String : Xd", LENGTH(str eu 1B + *A", LENGTH(str1)); Printf("\n Enter the First String gets(str1); pnintf("\n Enter the Second String : gets(str2); CONCAT(stri, str2); print#("\n Concatenated String : Xs", tri); break; printf("\n Enter the String gets(stri); print#("\n Enter the Position of a Substring scanf("X4", pos); pnint#("\n Enter the Length of a substring ‘scanf("%d" len); SUBSTR( str, pos, len); break; printf(*Enter the string : *)3 gets(stri); printf("Enter the string to be renoved : gets(substr); print#("Enter the string to replace gets(repstr); REPLACE(str1, substr,repstr); exit(0); printf(*\n Invalid Option"); break Ms a 5 i ‘string Operations 4. String Length 2.String Concatenation 3.Extracting Substring A.Replace 2 String 5.exit enter your choice: 2 Enter the First String : Flowers are beautiful 7 sein eee sesare beautiful | concatenated string £ FLOSTSAE A

You might also like