0% found this document useful (0 votes)
47 views24 pages

Daaaa

DAA practical file aktu

Uploaded by

qz5jq94yh2
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)
47 views24 pages

Daaaa

DAA practical file aktu

Uploaded by

qz5jq94yh2
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/ 24
S.No: 1 Exp. Name: Program in C for Recursive Linear Search AIM/OBJECTIVE:Program in 'C’ for Recursive Linear Search THEORY:Linear search is a search that finds an element in the list by searching the element sequentially until the element is found in the list. ALGORITHM: Linear Search ( Array A, Value x) Step 1: Set ito Step 2:ifi > n then go to step 7 Step 3: if Ali] = x then go to step 6 Step 4:Setitoi+1 Step 5: Go to Step 2 Step 6: Print Element x Found at index i and go to step & Step 7: Print element not found Step 8: Exit Source Code: linearSearch.c Int Reeurssvetsc Ant arr(], int value, int index, int 9 * se(index >= n> « > else if Carr[index] == value) « pos = index + 43 } else « Feturn Recursivels(arr, value, indexer, n>: y return poss) Ane maincrt Ent n, value, pos, m= 0, arr{100}: printéCrenter the total elenents in the array: “): seane("xd", an): printeC"enter the array elements: “): for (int 1-0; 4 © ny dee) « seant(Ma", @arr[i]); + prantecrenter the element to search seant("xd", value); pos = Recursivets(arr, value, @, n): Af (pos In 0) Printe("ELement found at positien Xd“, pes): } ese ¢ printf ("Element net found"); > ¥ Execution Results - all test cases have succeeded! Test Case - 1 User Output Enter the total elenents an the array) Zz 1245678 6 Elenent found at position 5 Test Case - 2 User Output Enter the total elements an the array, Enter the array elements 569 Enter the element to search a Element not found S.No: 2 Exp. Name: Program in C for Recursive Binary Search Aim: AIM/OBJECTIVE:Program in ‘C’ for Recursive Binary Search THEORY:On the other hand, a binary search is a search that finds the middle element in the list recursively until the middle element is matched with a searched element. Binary Search Algorithm: STEP1: Find the midpoint of the array; this will be the element at arr[size/2]. The midpoint divides the array into two smaller arrays: the lower half of the array consisting of elements 0 to midpoint - 1, and the upper half of the array consisting of elements midpoint to size - 1. STEP 2:Compare key to arr[midpoint] by calling the user function cmp_proc, STEP 3: If the key is a match, return arr{midpoint}; otherwise STEP 4: If the array consists of only one element return NULL, indicating that there is no match; otherwise STEP 5: If the key is less than the value extracted from arr{midpoint] search the lower half of the array by recursively calling search; otherwise STEP 6: Search the upper half of the array by recursively calling search Source Code: binarySearch.c include void binary search(int[], int, int, int); void bubble_sort(int [], int); int main(){ int key, size, 45 int List [25]; printf(“Enter size of a list: scanf("Xd", &size); printf("Enter elements: “); for(i = 25 i< sizes it) { scanf("Rd", @list[i]); — } bubble sort(list, size); printé(""); printf("Enter key to search: "); scanf(“d", &key); binary_search(list, @, size, key); } void bubble sort(int list[], int size){ int temp, 4, 35, for(i = 0; i< size; i++) = { for (j= is j < sizes j++) t if (list[i) > list(3]) t temp = list[il; List[i] = list{iIs List[j] = temp; + > void binary_search(int List[], int 1o, int hi, int key)( int mid; if(lo> hi) { printf("key not found\n"); return; t mid =(10 + hi) / 25 Af (list[mid] == key) { printf(*key found\n"); } else if (1ist{mid] > key) ¢ binary_search(list, lo, mid - 1, key); } else if (1ist[mid] < key) { binary_search(list, mid + 1, hi, key); n Execution Results - all test cases have succeeded! Test Case - 1 User Output Enter size of a list 4 Enter elenents: 2345 Enter key to search 3 Key found Test Case - 2 User Output Enter size of a list: 3 Enter elements 569 Enter_key to search: 10 Key not found S.No: 3 Exp. Name: Write a Program in ‘C’ for Selection Sort a OBJECTIVE:Write a Program in for Selection Sort THEORY:In selection sort, the smallest value among the unsorted elements of the array is selected in every pass and inserted to its appropriate position into the array. First, find the smallest element of the array and place it on the first position. Then, find the second smallest element of the array and place it on the second position. The process continues until we get the sorted array. The array with n elements is sorted by using n-1 pass of selection sort algorithm. 1.n Ist pass, smallest element of the array is to be found along with its index pos. then, swap A(0] and Alpos]. Thus [0] is sorted, we now have n -1 elements which are to be sorted. 2. [In 2nd pas, position pos of the smallest element present in the sub-array Aln-1] is found. Then, swap, Al] and Alpos]. Thus A[0] and Alt] are sorted, we now left with n-2 unsorted elements. 3. In n-Ith pass, position pos of the smaller element between A[n-1] and Aln-2] is to be found. Then, swap, Alpos] and Aln-1]. 4, Therefore, by following the above explained process, the elements A(0], A[1], Al2],... Aln-1] are sorted ALGORITHM: SELECTION SORT(ARR, N) Step 1: Repeat Steps 2 and 3 for K = 1 to N-1 Step 2: CALL SMALLEST(ARR, K, N, POS) ‘Step 3: SWAP AIK] with ARR[POS] [END OF LOOP] Step 4: EXIT SMALLEST (ARR, K, N, POS) Step 1: [INITIALIZE] SET SMALL = ARIK] Step 2: [INITIALIZE] SET POS = kK Step 3: Repeat for) = K+1 to N-1 IF SMALL > ARRU] SET SMALL = ARRUJ] SET POS = J (END OF IF] {END OF LOOP] Step 4: RETURN POS Source Code: Hincludecstdio.n> ine smallest (int[],int,int)s void main () { int a[109); nt 4,4, k,pos, temp; printf(’Enter the total elenents in the array: “)s scanf("8d" 8k); printf("Enter the array elements: for(int in0sicksiee){ scanf("%d",8a[i]); be For (1-0; ick; i+#){ posssmallest(a,k,i); temp=a[4]; a[il=a[pos]; alpos] = temp; } printf("printing sorted elements...\n*); for(i=@jickji++) { printf("%d ",a[i])5 +} int smallest(int a[], int n, int i) € int small, pos, J; small = a[i]; pos = i; For(j-itds jens j++) t if(a[J] void main () { int i, 4, k,temp; int a[100]; printf("Enter the total elements in the array: scanf("%d" 8k) printf("Enter the array elements: For (i=05ickjire){ scanf("%d" ,fa[i]) 5 i} printf("printing sorted elements...\n")5 for(i=1; ick; i++) { temp = afi]; 5-4-5 while(j>=@ && temp <= a[j]) { a(j+4] = afi] d= 5-43 } ai+1] = temp; } for(i { Os icksit+) printf("%d * # } Execution Results - All test cases have succeeded! Test Case - 1 User Output Enter the total elements in the array: 4 Enter the array elenents: 1097 101 printing sorted elenents... 79 10 101 Test Case - 2 User Output Enter the total elements in the array: 3 Enter the array elenents: -9 -78-90 printing sorted elements... -98 -78 -9 S.No: 5 Exp. Name: Write a Program in ‘C’ for Heap Sort OBJECTIVE:Write a Program in 'C’ for Heap Sort THEORY:Heap sort processes the elements by creating the min heap or max heap using the elements of the given array. Min heap or max heap represents the ordering of the array in which root element represents the minimum or maximum element of the array. At each step, the root element of the heap gets deleted and stored into the sorted array and the heap will again be heapified The heap sort basically recursively performs two main operations + Build a heap H, using the elements of ARR. + Repeatedly delete the root element of the heap formed in phase 1. ALGORITHM: HEAP_SORT(ARR, N) Step1: [Build Heap H] Repeat for i=0 to N-1 CALL INSERT HEAP(ARR, N, ARRIi)) [END OF LOOP] Step 2: Repeatedly Delete the root element Repeat while N > 0 CALL Delete_Heap(ARR.N, VAL) SETN= N41 [END OF LOOP] Step 3: END Source Cod heapSort #includecstdio.h> int temp; void heapify(int arr[], int size, int 4) { int largest = 13 int left =2* i445 int right = 24+ 25 Af (left ¢ size aa arr[left] > arr[largest]) largest = left; Af (night ¢ size @@ arr[night] > arr{largest]) Largest = right: if (largest. I= 4) { temp = aril; arr[i] = arr{largest]; arr[largest] = temps heapify(are, size, largest); > > void heapSort(int arr[], int size) { int i for (i= size / 2-1; 1 >= 0; 1--) heapify(arr, size, i); for (i = size - 45 i { temp = arr[@]; arr[®] = arr[i]; arr[i] = temp; heapify(arr, i, 8); i void main() { int arr[100]; int 43 int sizes printf("Enter array size scanf("%d", &size); printf("Enter %d elements : for (i = @; ix size; it+) scanF("%d", Sarr[i]); printf("Before sorting the elements are for (i = @; i < size; i++) printf("xd “, arr[i]); heapSort(arr, size); printf("\nAfter sorting the elements are : » size); for (i = @; i < size; it+) t print#("%d ", arefi])5 + printf ("\n"); Execution Results - all test cases have succeeded! Test Case - 1 User Output Enter array size : 10 Enter 10 elements : 110 23412100232 Before sorting the elements are : 110234 12 100 232 ‘After sorting the elenents are : 1122234 10 23 108 S.No: 6 Exp. Name: Write a Program in ‘C' for Merge Sort JECTIVE:Write a Program in ‘C’ for Merge Sort THEORY: Merge sort is the algorithm which follows divide and conquer approach. Consider an array A of n number of elements. The algorithm processes the elements in 3 steps. 5.If A Contains 0 or 1 elements then it is already sorted, otherwise, Divide A into two sub-array of equal number of elements. 6. Conquer means sort the two sub-arrays recursively using the merge sort. 7. Combine the sub-arrays to form a single final sorted array maintaining the ordering of the array. The main idea behind merge sort is that, the short list takes less time to be sorted. ALGORITHM: MERGE Step 1: (INITIALIZE] SET | = BEG, J = MID + 1, INDEX = 0 Step 2: Repeat while (| <= MID) AND (J<=END) IF ARRII] < ARRU SET TEMP[INDEX] = ARR(I] SETI=1+1 ELSE SET TEMP[INDEX] = ARRU) SET) =J+1 [END OF IF] SET INDEX = INDEX +1 [END OF LOOP] Step 3: [Copy the remaining elements of right sub-array, if any] IF > MID Repeat while J <= END SET TEMP[INDEX] = ARR) SET INDEX = INDEX + 1, SETJ=J +1 [END OF LOOP] [Copy the remaining elements of left sub-array, if any] ELSE Repeat while | <= MID ‘SET TEMP[INDEX] = ARR{I} SET INDEX = INDEX + 1, SETI=1+1 [END OF LOOP} [END OF IF] Step 4: [Copy the contents of TEMP back to ARR) SET K Step 5: Repeat while K < INDEX SET ARRIK] = TEMP[K] SETK=K +1 [END OF LOOP} Step 6: Exit MERGE_SORT(ARR, BEG, END) Source Code: #include void mergeSort(int [], int, int, int); void partition(int [],int, int); int main() t int List [50]; int i, size; printf("Enter array size : scanf("%d", @size); printf("Enter %d elenents : for(i = 0; i < sizes i+) { * size); scanf(" a", listli]); } printf("Before sorting the elements are : "); for(isO;icsizesit+) { print#("%d ", List[i]); } partition(list, 9, size - 1); printf("\nafter sorting the elements are for(i = @:1 < size; i++) { printf(*ed ",1ist{i])3 } print#("\n")3 return @; } void partition(int list[],int 1ow,int high) { int mid; if(low < high) { mid = (low + high) / 25 partition(List, low, mid); partition(List, mid + 1, high); mergeSort(list, low, mid, high); y void mergeSort(int list[],int low,int mid, int high) t int i, mi, k, lo,temp[59]; lo = low; 4 = Lows mi = mid +4; while ((1o <= mid) && (mi <= high)) { if (list[lo] <= list[mi]) { temp[i] = list[1o]; love; } else } > if (lo > mid) t for (k = mis k <= high; ke+) t temp[i] = list[k]; ines } > else t for (k = lo; k <= mid; k++) i temp[i] = list[k]; ins } } for (k = low; k <= highs k++) t List[k] = tempfk]; > , Execution Results - All test cases have succeeded! Test Case - 1 User Output Enter array size = 5 Enter 5 elenents 25467 Before sorting the elenents are: 25467 After sorting the elenents are : 245 67 Test Case - 2 User Output Enter array size + 3 Enter 3 elenents = 23150 Before sorting the elenents are : 23 15 0 After sorting the elenents are: @ 15 23 S.No: 7 Exp. Name: Write a Program in ‘C’ for Quick Sort OBJECTIVE: Write a Program in 'C’ forQuick Sort THEORY: Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as, d partitions the given array around the picked pivot. There are many different versions of quickSort wsat pick pivot in different ways. 8. Always pick first element as pivot. 9, Always pick last element as pivot (implemented below) 10, Pick a random element as pivot. 11. Pick median as pivot. The key process in quickSort is partition). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time, ALGORITHM: SOURCE CODE: PARTITION (ARR, BEG, END, LOC) Step 1: [INITIALIZE] SET LEFT = BEG, RIGHT = END, LOC = BEG, FLAG = Step 2: Repeat Steps 3 to 6 while FLAG = Step 3: Repeat while ARRILOC] <=ARRIRIGHT] AND LOC != RIGHT SET RIGHT = RIGHT - 1 [END OF LOOP} Step 4: IF LOC = RIGHT SET FLAG =1 ELSE IF ARRILOC] > ARRIRIGHT] SWAP ARRILOC] with ARRIRIGHT] SET LOC = RIGHT [END OF IF] Step 5: IF FLAG = 0 Repeat while ARR[LOC] >= ARRILEFT] AND LOC SET LEFT = LEFT +1 [END OF LOOP] Step 6:IF LOC = LEFT SET FLAG = 1 ELSE IF ARRILOC] < ARRILEFT] SWAP ARRILOC] with ARRILEFT] SET LOC = LEFT [END OF IF] [END OF IF] Step 7: [END OF LOOP] Step & END LerT QUICK SORT (ARR, BEG, END) Step 1: IF (BEG < END) CALL PARTITION (ARR, BEG, END, LOC) CALL QUICKSORT(ARR, BEG, LOC - 1) CALL QUICKSORT(ARR, LOC + 1, END) [END OF IF} Step 2: END Source Cod ksort.c qu: Hincludecstdio.h> void quicksort(int number[25], int first, int last) { int i, j, pivot, temp; if (First < last) { pivot = first; A= first; j = last; while (4 < 4) { while (nunber[i] <= nunber[pivot] 8& i < last) \while(nunber(j] > number[pivot]) ie if (13) t temp = number[i]; number[i] = nunber(3]3 number[3] = temps t y tenp = nunber[pivot]; nunber[pivot] = nunber{j]; runber[j] = temp; quicksort (number , first, J -1); quicksort(number , j + 1, last); y t Ant main() { int count, number{25]5 printf("Enter array size : seanf("Nd", &count) ; printf(“Enter %d elements : *, count); for (int i= 8; 4 ¢ count; i+) scanf("Kd", &nunber[i]); printf("Before sorting the elements are : for (int i= 8; i ¢ counts i+) { printf("%d *,number[i])5 + quicksort(number, @, count - 1); printf("\nafter sorting the elements are : for (int i= 8; 1 < counts i++) print#("Xd ",number(i]) 5 print#("\n")5 return Execution Results - All test cases have succeeded! Test Case - 1 User Output Enter array size 5 Enter 5 elements : 12 35 78965 Before sorting the elements are : 12 35 78 96 5 ‘After sorting the elements are 75 12 35 78 96 Test Case - 2 User Output Enter array size 3 Enter 3 elements -56 -4-3 Before sorting the elements are -56 -4 -3 After sorting the elements are : “56 -4 3 S.No: 8 Exp. Name: Write a Program in ‘C’ for Counting Sort OBJECTIVE:Write a Program in ‘C’ forCounting Sort THEORY:Counting sort is a sorting technique based on keys between a specific range. Itsorts the elements of an array by counting the number of occurrences of each unique element in the array. The count is stored in an auxiliary array and the sorting is done by mapping the count as an index of the auxiliary array.. ALGORITHM: Counting Sort (array P, array Q, int k) 1.Fori—1tok 2.do Cli] - Otok 3. forj~ 1 to length [A] 4, do CIAUI ~ C [A {l]+110(n) times) Sfor it 2 tok 6. do C [iJ+C [i] + Cli-1] [8(k) times] 7 for j ~ length [A] down to 1 [6(n) times} 8. do BICIAGI~A UI 9, CIAGI-CIAGI-1 Source Code: count ingSort.c Hincludecstdio.h> void counting sort (int Af], int k, int n) { int i453 int 8[15],¢[290]3 for (i = 0; ic= kj ite) cLa] = 83 for (je1sje=nje+) C{AL5]}] = CLALS]]+25 for(i=1si c= ksie+) cLa] = Cli] + CLi-1]; for(j = njj>=1;3--) { BECLALSII] = ALII5 CEALI]] = CIALI]] - a5 y printf("The Sorted array is = for(iatjicenjit+) print #(*%d *,B[i])5 3 int main() ( int n,k = @,A[15],i; printf("Enter the nunber of inputs : scanf("Xd" ,&n) ; printf ("Enter the elements to be sorted : for(i = 1;i <= njit+) { scanf( "Xd", 8AL1]) 5 if(A[i] > k) { k = ALiIs + > counting_sort(A,k,n); print#("\n")5 return 0; } Execution Results - ll test cases have succeeded! Test Case-1 User Output Enter the number of inputs : 8 Enter the elenents to be sorted : 84228331 The Sorted array is: 12233488 Test Case - 2 User Output Enter the number of inputs 3 Enter the elenents to be sorted : 491 The Sorted array is: 149 Exp. Name: Write a Program in ‘C’ for Travelling SNes9 Salesman Problem using Dynamic Programming OBJECTIVE:Write a Program in 'C’ for Travelling Salesman Problem using Dynamic Programming THEORY:In the traveling salesman Problem, a salesman must visits n cities. We can say that salesman wishes to make a tour or Hamiltonian cycle, visiting each city exactly once and finishing at the city he starts from, There is a non-negative cost ¢ (i,j) to travel from the city i to city j. The goal is to find a tour of minimum cost. We assume that every two cities are connected, Such problems are called Traveling-salesman problem (TSP). ALGORITHM: Algorithm: Traveling-Salesman-Problem can, =o for s = 2tondo for all subsets S € (1,2, 3, .., n} of sizes and containing 1 CES, 1)=0 for all €S andj #1 C(S,j) = min {C (S- G}, i) + dU. j) fori S andi # jp Return minj C (1, 2 3, 4 Mj) + 4G, 0) Source Code: travellingSalesMar #includecstdio.h> int ary[10][10], completed[10] ,n, cost=0; void takeInput() { int 4.95 printf("Enter the number of villages: seanf("%d" 8); printf("Enter the Cost Matrix\n"); for(is@;i < asite) d printf("enter Elements of Row: d\n",i+1); for( 5-055 " citys); ncity=least(city); "Xd" zncity+1) 5 cost+=ary[city] [neity]; returns } mincost(ncity) ; int least(int c) di int i,nc=9995 int min=999, kmin; for(is0;i < nsitt) { if((ary[e] [1] !=0)8&(completed[i]=-0)) if(ary[c][il+aryLi}fe] < min) t ry [i] [@]+ary[c] [i]s ary(c] [ils } } if(min!=999) cost+=kmin5 return nes ‘takeInput(); printf("\nThe Path is:\\ mincost(@); print£("\nlinimum cost is %d ",cost); return @; Execution Results - All test cases have succeeded! Test Case - 1 User Output Enter the number of villages 4 Enter the Cost Matrix Enter Elements of Row: 1. 0413 Enter Elements of Row: 2 4021 Enter Elements of Row: 3 1205 Enter Elements of Row: 4 3150 The cost list is: @ 4 1 3 4 @ 2 1 1 2 @ 5 3 1 5 @ The Path is: 1 >3--=>2-- pao Minimum cost is 7 Exp. Name: Write a Program for Find Minimum SNO10 Spanning Tree using Kruskal's Algorithm OBJECTIVE: Write a Program forFind Minimum Spanning Tree using Kruskal’s Algorithm THEORY:Given a connected and undirected graph, a spanning tree of that graph is a subgraph that is a tree and connects all the vertices together. A single graph can have many different spanning trees. A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected, undirected graph is a spanning tree with a weight less than or equal to the weight of every other spanning tree. The weight of a spanning tree is the sum of weights given to each edge of the spanning tree. ALGORITHM: Algorithm Kruskal(G,w) { A:= @ for each vertex v € VIG] do MAKE-SET(v) Sort the edges of E into nondecreasing order by weight w for each edge (u, v) € E, taken in nondecreasing order by weight do if FIND-SET(u) = FIND-SET() then ( A= Av itu, vi} UNION(u, v) } return A Source Code: kruskal’ sAlgorithy Hincludecstdio.h> Hincludecconio.h> Hincludecstdlib.h> int 4,,k,a,b,u,v,n,ne=15 int min, mincost=0,cost[(9][9],parent[9]j int Find int); int uni (int, int); void main() { printf("Inplenentation of Kruskal's algorithm\n"); printf("Enter the no. of vertices: "); scanf("%d" ,8n); printf(“Enter the cost adjacency matrix\n"); for(i=1jic=njit+) { for(j=1;je=njj++) i scanf("¥d",@cost[i}[])5 if(cost[i][j]==0) cost Li] [4]=999; ry print#("The edges of Minimum Cost Spanning Tree are: "); while(necn) { for(i=1 jmin=999; ic=n; i++) { S++) 4#(cost[ 4] [J]

You might also like