You are on page 1of 60
Design and Analysis of Algorithms RJS POLYTECHNIC, BENGALURU ‘Vinayaka VM | Computer Science | August 24, 2017 Prerequis ites Knowledge of Data Structures, Course Objectives 1, Write sorting programs using Divide-and-Conguer techniques. 2. Implement to find the minimum cost spanning tree and shortest path using different Greedy techniques. 3. Construct DFS, BFS programs and topological ordering using Decrease-and-Conquer technique. 4, Implement knapsack, travelling salesperson, Course Outcome On successful completion of the course, the students will be able to attain CO: Course Outcome Experiment linked cL Teaching Hrs col coz Demonstrate Quick sort and Merge sort and calculate the time required to sort the elements. Implement the topological ordering of vertices, travelling salesman problem and Knapsack problem. 12 3t05 U,A,AL UA 12 18 co3 co4 cos Construct programs to check graph is connected or not using BFS and DFS methods Implement programs on| divide and conquer, decrease and conquer Experiment finding the minimum cost of spanning tree using Prim’s algorithms and shortest path using Dijkstra’ algorithm. 67 89 10,11 U,A,AL U,A,AL UA,AL Total sessions 18 8 \VIM.VINAYAKA erseu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE | RJS Polytechnic, KRJS Group of Institutions, Koramangala, Bengaluru \ RIS Polytechnic was established in the year 1985 - 86 by Karnataka Reddy Jana Sangha under ED 60 MPI 84, dated : 06-10-1984. RJS Polytechnic started it's journey with humble beginning with Diploma in Commercial Practice. RIS Polytechnic has made ‘great strides in the field of technical education right from it's inception in the year 1985- 86. RIS Polytechnic is situated in a serene surrounding and located in koramangala, Bangalore-34. It is located in such a place that itis able to serve the cause of Students of both urban and rural areas of Bangalore in particular and the state of Karnataka and India in general. RIS Polytechnic is run by Kamataka Reddy Jana Sangha(KRIS) , a non-profit registered body, under self financing scheme and it consists of a galaxy of personalities from all walks of life. RIS Polytechnic is affiliated to the Directorate of Technical education, recognized by the Government of Karnataka and approved by All India Council for Technical Education (AICTE), New Delhi. The affairs of RIS Polytechnic is managed by a constituted Governing Council By KRIS. Vinayaka V.M. , Lecturer Computer Science Department, RJS Polytechnic. Qualified with M.Tech., GATE, and KSET. Work experience in Bapuji Instiute of Engineering and Technology, Davanagere. LV M.VINAYAKA yrnes. LECTURER, COMPUTER SCIENCE DEPARTMENT, RJS POLYTECHNIC, KORAMANGALA PAGE? Table of contents 1 Sorta given set of elements using the Quick sort method and determine the time required to sort the elements. Repeat the experiment for different values of n. 2 Sort a given set of elements using merge sort method and determine the time required to sort the elements. Repeat the experiment for different of values of n 3 Write a program to obtain the topological ordering of vertices in a given digraph, 4 Implement travelling salesman problem, 5 Implement the knapsack problen ony 6 Print all the nodes reachable from a given starting node in a digraph using BFS method, 7 Check whether a given graph is connected or not using DFS method. 8 Write a program to implement binary search using divide and conquer technique ‘9 Write a program to implement insertion sort using decrease and conquer technique 10 Find minimum cost spanning tree of a given undirected path using a Prim’s algorithm, 11 From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra’s algorithm, \VMVINAYAKA jrnen, LECTURER, COMPUTER SCIENCE DI PAGE? "ARTMENT, RIS POLYTECH 1 Sort a given set of elements using the Quick sort method and determine the time required to sort the elements. Repeat the experiment for different values of n. ALGORITHM Quicksori(A[left.right)) Sorts a subarray by quicksort Minput: Subarray A[0..n-1] Output: Subarray Alleft.right] sorted in increasing order if left < right split€ Partition (Alleft.. right) split is split position bisecting array A Quicksort(Afleft.. split-1)) Quicksort(Afsplit+1 .right)) ALGORITHM Partition(A[left..right)) Splits a subarray using first element as a pivot ‘Munput: Subarray of array A[O..n-1] ‘Output: Partition of Afleft.right], with split position retuned pivot@Alleft] i € left; j © right+1 repeat repeat i € i+] until A[i[>=pivot repeat j € j-1 until Alj}<=pivot swap(Ali]. AG) until >=} swap(ALi}AGiD) swap (Alleft],Alright)) retum j Explanation of the concept: - Quick sort sorts by employing a divide and conquer Strategy to divide a list into sublists. The steps are as follows: Step 1: Pick an element, called a pivot from the list. Step 2: Reorder the list so that all the elements which are less than the pivot come before the pivot and so that all elements greater than the pivot come after it. After this pattitioning, the pivot is in its final position. Step 3: Recursively sort the sublist of lesser elements and the sublist of greater elements. C code: Hinclude Hinclude #include ‘fincludestime.h> #define SIZE 10 void Quick(int A[SIZE},int int); int partition(int A[SIZE].int.int); void swap(int A[SIZE], int int*); LV M.VINAYAKA jrnen. LECTURER, COMPUTER SCIENCI PAGES DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, itn; int main) { clock_t begin,end; double time_required; cliser(); scanf("%ed",&en); for(i=0;isnsi++) { printf("Enter the number %d:".i+1); scant("%d",&ALi); } begin=clock(; Quick(A,0.n-1); end=clock(); printf("\n print{("\n Sorted elements are:\n"); print for(i-O;ismji+) printi("\t 9d" ALi): time_required=1.0* (double)(end-begin)); printf("\n The time required is :%f",time_required); getch0) return 0: } int partition(int A[SIZE] int low int high) { int pivot=A[low]. while(i<=j) { yw, johigh; while(Ali}<=pivot) it while(Alj}>pivot) is itis) swap(A.&e, ej); } swap(A,élow,8j); return j; } void swap(int A[SIZE} int *iint *)) { AL*i}=temp: } void Quick(int A{SIZE],int low int high) { LV M.VINAYAKA jernen. LECTURER, COMPUTER SCIENCI PAGES DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, int mi; if(lowshigh) { m=partition(A.low.high): delay(1000); Quick(A.low,m-1); Quick(A.m+1,high); ourPuT: Sorting using Quick sort Enter the total number of elements: 5 Enter the number 1:2 Enter the number 2 : 6 Enter the number 3 : 4 Enter the number 4: 9 Enter the number 5 : 1 Sorted elements are I 34 6 9 ‘The time required is : $3.800000 0 1 2 3 4 i j 2 6 4 9 1 i ij 2 1 4 9 6 ij 2 1 4 9 6 i i 2 1 4 9 6 ij i i 1 2 4 9 6 ij 1 2 4 9 6 i i 1 2 4 9 6 5 1 2 4 9 6 ii 1 2 4 9 6 1 2 4 6 9 1 2 4 6 9 1 2 4 6 9 \VIM.VINAYAKA secu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGES JAVA CODE: import java.util. Random; import java.util. Scanner, public class quicksort { static int max=2000; int partition (int{] a, int low.int high) { int p.igtemp; p=allow]; islow+l; jehigh; while(ow high) { while(ali]<=p&&ishigh) itt: while(alj}>p) in ints) afi}=alj); afjlstemp: } else { temp=aflow]; aljl=temp: return j; } } retum j; } ‘void sort(int[]a,int low,int high) dow tity { int -partition(a low high); sort(alow,s-1); sort(a,s+1,high); } } public static void main(String{J args) ( 1 TODO Auto-generated method stub imt{] a; inti; System.out printIn( "Enter the array size") Scanner sc =new Seanner(System.in) int n=se.nextlnt(; a= new int{max]; Random generator=new Random(); for( i=O;ism;i++) LV M.VINAYAKA jenn. LECTURER, COMPUTER SCIENCI PAGE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, afi]=generator.nextInt(20); System.out printhn(" Array before sortin for( i=O;ismsit+) System.out.printin(ali}+" "); ong startTime=System.nanoTime() quicksort m=new quicksort(); msort(a.0.n-1); ystem.nanoTime(); Jong elapseTime=(stopTime-startTime); System.out printin("Time taken to sort array is:"+elapseTime+"nano seconds"); System.out printin("Sorted array is"); for(i=O;i Hinclude Hinclude ‘fincludetime.h> int mainQ) { int i low high,n: int A[10]; clock_t begin,end; double time_required; VM.VINAYAKA jrnen. LECTURER, COMPUTER SCIENCI PAGE 12, DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, } void MergeSort(int A{10} int low int high); void Display int A[10] int n); clrser(); printi("\nin Sorting using merge sort\n"): print{("\n How many elements are there?\n"); seanf("%ed" en), printi("\n Enter the elements:\n"); for(i=O:isnsi++) scanf("%d",& ALi); low=0; high=n-1; begin=clock(); MergeSort(A.low,high); end=clockQ; Display(A.n) time_required=1.0*((double)(end-begin)/CLOCKS_PER_SEC; printi("\n The time required is:%2f".time_required); getch(); return 0; void MergeSort(int A[10] int low,int high) { } int mid; void combine(int A(10],int low. int mid,int high); if(lowshigh) { mid=(ow+high)/2; MergeSort(A low,mid): MergeSort(A.mid+1,high): Delay(1000); combine(A.low,mid high); d Void combine(int A[10],int low. int mid,int high) { intik; int temp[10}; i 5 while(i<-mid&é&ej #include define TRUE I define FALSE 0 int main) { int ijk, {nt n,a{10]{10} in{ 10}. visit 10] int count=0; \VM.VINAYAKA sernen. LECTURER, COMPUTER SCIENCI PAGE 17 DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, for(j=0;j adjf]; // Adjacency List /Constructor Graph(int v) { Vey; adj = new LinkedList[v}; for (int i=0; i it = adj[v].iterator(); while (it.hasNext()) { i=itnext(); if (Ivisited[i}) topologicalSortUtil(i, visited, stack); } // Push current vertex to stack which stores result stack.push(new Integer(v)); } /I The function to do Topological Sort. It uses // recursive topologicalSortUtilO, void topologicalSort() { Stack stack = new Stack(); 1 Mark all the vertices as not visited boolean visited[] = new boolean[V]; for (int i = 0; i < V; i+4) visited[i] = false; // Call the recursive helper function to store 1! Topological Sort starting from all vertices // one by one for (int i= 0; i < V; i++) if (visited{i] == false) topologicalSortUtilG, visited, stack); \VM.VINAYAKA erseu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 20, // Print contents of stack while (stack.empty Ise) System.out.print(stack.pop() + "" } 1! Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(6); INPUTGRAPH: g.addEdge(S, 2); g.addEdge(5, 0); (*) g.addEdge(4, 0): g.addEdge(4, 1); g.addEdge(2, 3): (7) g.addEdge(3, 1); System.out printin("Following is a Topological " +"sort of the given graph"); g.topologicalSort(); } Output: Following is a Topological sort of the given graph 542310 © Oe ‘ ee © gooceno edi \VIM.VINAYAKA rseu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 21 4 Implement travelling salesman problem. ALGORITHM Travelling Salesman Step1: Generate a set of all the tours starting from and ending at city ‘1° Step2: Calculate length of all the tours generated in step1. ‘Step3: Select the minimum length tour as the optimal solution. If more than one such tours exist, break the tie randomly. include void main() { int ij, CostFrom| 10}{10].numberofcities, path{10],minimumcost; elrser); ‘minimumcost=9999; printf("\n TRAVELLING SALES MAN PROGRAM\n"); print{("\nTThe number of cities is 4\n"); printf("Enter the distance form city to eity\n"); forli=0:i<4:i++) CostFromfi]fi for (i=Oi152.53.50"); path[0]=CostFrom[0}| 1}+CostFrom[1]{2]+CostFrom[2][3]}+CostFrom[3][0]; printf("\nCost of this path is %d\n",path[O}); >2>3>150"), path{1]=CostFrom[0][2]+CostFrom[2][3]+CostFrom[3][1]+CostFrom[1]0]; ‘Cost of this path is Zed\n" path(]); "05352-5150"; path[2]=CostFrom[0][3]+CostFrom[3][2}+CostFrom|2][1]+CostFrom{1 [0]; printf("\nCost of this path is %d\n" path[2]); printf("0->1-53->2->0"); path[3]=CostFrom[0)|[1]+CostFrom[1][3]+CostFrom[3][2}+CostFrom[2][0]; printf("\WnCost of this path is Zd\n" path(3)); >2->1->3-30"); -CostFrom|0}[2]+CostFrom[2][1]+CostFrom| 1][3]+CostFrom(3][0}; print{("\nCost of this path is %d\n"path[4)); printf("0->3->1->2->0"); path{5}=CostFrom|0][3]+CostFrom[3}[1]+CostFrom{1][2]+CostFrom{2][0}; \VM.VINAYAKA jrnen. LECTURER, COMPUTER SCIENCI PAGE 22 DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, printf("\nCost of this path is d\n" path{S));, forli=0:i<6:i+4) { } printf("\nThe optimal solution costs %ed\n",minimumcost); getch(); minimumco: (minimumeost"); weight[i][j]=s.nextInt(); } } System.out printin(); System.out.printin("Starting node assumed to be node 1."); eval(); } public int COST (int currentNode, int inputSet[] int setSize) { if(setSize==0) return weight[currentNode][0]; int min=INF; int set ToBePassedOnToNextCallOfCOST[ ]=new int[n-1]; for(int i=0;i 4 Enter weight of 1 to 2: Enter weight of 1 to 3 Enter weight of 1 to 4: Enter weight of 2 to L Enter weight of 2 to 3: Enter weight of 2 to 4: Enter weight of 3 to 1 Enter weight of 3 to 2: Enter weight of 3 to 4: Enter weight of 4 to 1 Enter weight of 4 to 2: Enter weight of 4 to 3: Starting node assumed to be node 1. The tour is 1-2-4-3-1 The final cost is 11 TOUR LENGTH 192939491 484147 = 18 193929491 5484347 = 23 194929391 7434845 = 23 194939291 4+148+2 = 18 192349391 1= 2434145 =11 optimal 193349291 1=5414342=11 optimal 5 Implement the knapsack problem (0/1). ALGORITHM Knapsack Step1: Generate all the combinations of given items in a subset. Step2: Calculate total weight of all the subsets generated in step. Step3: Eliminate the subsets whose total weight exceeds the capacity of knapsack, Step4: Calculate total value of items in each subset that is remaining ‘StepS: Select the subset which has highest total value as the feasible solution, If there are more than one such subsets, break the tie randomly, #include #includesconio.h> Hinclude int table[5][6]; void main() int w{ J=(0,2,3,4.5); int v{ J=(0.3,4.5,6) int W=5; \VIM.VINAYAKA rpeu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 27 int n=4; int ij void DKP(nt a, int W, int w/], int v{)); clrser print{("\n\e\ O/1 Knapsack Problem"); for (i=0:i<=n;i++) { for (j=0;j<=Wij+4) { ) tablefil[j]=0; ) DKP(a,Ww.); etch); ) void DKP(nt n, int W. int w[5], int v[5}) { void find_item(int ,int inti: int val val2; forli=0;is=nji++) { for(j-0;5<-W3j+4) nt(): for(i=li<=nii++) ( for(j=1jWiit4) { it(=wli)) { vall=tableti-11U]s val2=v(i}+tablei-1](/-w(il}: table[il[j]=(val1>val2?vall:val2); } } } printf("\n Table constructed \n"); for (i=0:iO && k>0) * scabies ‘ printf("\nltem %ed is selected” i); Seti bbleli-11[k)) OUTPUT: O/1 Knapsack Problem ‘Table constructed 000000 003333 003447 003457 003457 For the Knapsack, Item 2is selected Item 1 is selected Capacity " Weight=5 KG SKG Value=6 Rs. Bag Ttem 1 Item 2 Ttem 3 Ttem 4 Subset Total weight Total value Null {1} (2) (3) {a} {12} (1,3) {1,4} (2.3) (2.4) (3.4) \VM.VINAYAKA jenn. LECTURER, COMPUTER SCIENCI PAGE 29, DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, (1.2.3) (1.2.4) (3.4) (2.3.4) (1.2.3.4) CAPACITY OF BAG IS 5 KG; So in the subset of items less than or equal to 5 KG {1,2} has highest value. Hence we select item 1 and item 2. Java Code: import java.util. Scanner; public class knapsackDP { pe * @param args */ public void solve(int{] wt, int(] val, int W, int N) { int ij; int(][] sol = new int{N + 1][W + 1]; for (i = 0; i <=N; i++) { for (j =0; j <= Ws j++) sol{i][j]=0; else if(wt{i]>j) solfi}[j}=sol[i-1][j); else sol[i][j]=Math.max((solfi- AIG), GSolfi - 1]Lj - weil] + vallil)); } System.out.printIn("The optimal solution is"+sol[N][W]); int{] selected = new int{N + 1]; for(i=0;i0&&j>0) { \VM.VINAYAKA yeneu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 30 if (sollil{j] !=solli-1][i)) { selected{i] = j- weil; iy } System.out.printIn("\nltems selected : "); for (i= Ls < N+ 1s i++) if (selected[i] == 1) System.out.print(i +" "); System.out.printIn); } public static void main(String[] args) { Scanner scan = new Scanner(System in); knapsackDP ks = new knapsackDP(); System.out.printIn("Enter number of elements "); int n = scan.nextInt(); int{] wt = new int{n + 1); int{] val = new int[n + 1]; System.out.printin("\nEnter weight for "+n +" elements"); for (int i= 1;i <=; i++) wt[i] = scan.nextInt(); System.out.printIn("\nEnter value for "+ n +" elements"); for (int i= 1;i <= ms i++) valli] = scan.nextInt(); System.out.printIn("\nEnter knapsack weight "); int W = scan.nextInt(); ks.solve(wt, val, W, n); } } Output: Enter number of elements 4 Enter weight for 4 elements 2132 Enter value for 4 elements 12 10 20 \VIM.VINAYAKA seneu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE) 15 Enter knapsack weight 5 The optimal solution is 37 Items selected : 1 2 4 Subset Total weight Total value Null 0 0 {1} 2 12 1 10 3 20 4 15 12+10=22 12+20=22 10+20=30 10+15=25 3 20+15=35 2+14+3=6 12+10+20=42 24+142=5 12+10+15=37 OPTIMAL 2434257 12+20+15=47 14+34+2=6 10+20+15=45 (1,2,3,4} 2+143+2=8 12+10+20+15=57 CAPACITY OF BAG IS 5 KG; So in the subset of items less than or equal to 5 KG {1,2,4} has highest value. Hence we select item 1, item 2 and item 4. Weight=2 KG Value-15 Rs Bag Item 1 Ttem 2 Ttem 3 Ttem 4 \VIM.VINAYAKA seneu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 32 6 Print all the nodes reachable from a given starting node in a digraph using BFS method. ALGORITHM BFS(G) i Implements a breadth first search waversal of a given graph i Input: Graph G= Output: Graph G with its verticies marked with consecutive integers in the order they are visited by the BFS traversal mark each vertex VERT with 0 as a mark of being “not visited” count© 0 for cach vertex v in VERT do if'v is marked with 0 dis(v) bis(v) Ihisit all the unvisited vertices connected to vertex v by a path and numbers them in the order they are visited via global variable count count€ count +1; mark v with count and initialize a queue with v while the queue is not empty do for each vertex w in VERT adjacent to the front vertex do if w is marked with 0 count € count +1; mark w with count add w to the queue remove the front vertex from the queue C code: Hinclude #include #include ‘define size 20 ‘define TRUE 1 define FALSE 0 int glsizel[size]; int visit[size]; int qlsize]; int front,rear; int void main() ( int v1,v2; char ans; void create(),bfs(int v1); ans='y’; clrscr(); created) clrscr(); printf("The adjacency matrix for the graph is\n"); for(v1=0;v1 - intre the vertex from which you want to traverse:"); printi("invalid vertex\n"); else { print{("The breath first search of the graph is\n"); bis(vl); getchi); } printf("\n Do you want to traverse from any other node?"); an exit(O); } ‘void create() { int v1.v2; char ans; ans’ print{("\n This is a program to creat a graph’) printi("\n The display is in breadth first manner"); print{("\n Entre number of nodes: "); scanf("“ed",&en); for(v1=0;vI=n)lv2>=n) printi("invalid vertex value\n") else { alvil[v2]=TRUE; glv2][v1]=TRUE; } printf("\n\n Add more edges?%(y/n)"); ans=getche(); }while(ans } void bfs(int v1) { VM.VINAYAKA jrnen. LECTURER, COMPUTER SCIENCI PAGE 34 DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, while(front!=rear) { vi=gt++front); printf("“ed\n".v1); for(v2=0;v2 queue; public BFSQ) { queue = new LinkedList(); } public void bfs(int adjacency_matrix{][], int source) { int number_of_nodes = adjacency_matrix[source].length - 1; int[] visited = new int{number_ int i, element; f_nodes + 1]; visited[source] \VIM.VINAYAKA erseu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 36, queue.add(source); while (Iqueue.isEmpty() { element = queue.remove(); i=element; System.out.print(i + "\"); while (i <= number_of_nodes) { if (adjacency_matrix{element][i] == 1 && visited[i] == 0) queue.add(i); visited[i] = 1; } iH; } } } public static void main(String... arg) { int number_no_nodes, source; Scanner scanner = null; uy { System.out printIn("Enter the number of nodes in the graph"); scanner = new Scanner(System in); number_no_nodes = scanner.nextInt(); int adjacency_matrix{][] = new int{number_no_nodes + 1J[number_no_nodes + 1]; System.out.printIn("Enter the adjacency matrix"); for (int i = 1; i <= number_no_nodes; i+) for (int j = 1; j <= number_no_nodes; j++) adjacency_matrix[iJ[j] = scanner.nextInt(); System.out println("Enter the source for the graph"); source = scanner.nextInt(); System.out printin("The BFS traversal of the graph is "); BES bfs = new BFS(; \VM.VINAYAKA secu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 7 bfs.bfs(adjacency_matrix, source); } catch (InputMismatchException inputMismatch) { System.out.printIn("Wrong Input Format"); } scanner.close(); } } Output : Enter the number of nodes in the graph 4 Enter the adjacency matrix o101 0010 0101 0001 Enter the source for the graph 1 The BES traversal of the graph is 1 2 4 3 01 12 23 34 Graph Traversal Sequence BES with tree and cross edges Shown in solid and dotted line \VIM.VINAYAKA secu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 38 7 Check whether a given graph is connected or not using DFS method. ALGORITHM DFS(G) /Mmplements a depth first search traversal of a given graph I Input: Graph G = 1/ Output: Graph G with its vertices marked with consecutive integers in the order they are first encountered by the DFS traversal mark each vertex in VERT with 0 as a mark of being “not visited” count € 0 for each vertex v in VERT do if v is markded with 0 dts(v) dfs(v) Ihistis recursively all the unvited vertices connected to vertex v by 2 path and numbers them in the order they are encountered via a global variable count count € count +1; mark v with count for each vertex w in VERT adjacent to v do if w is marked with 0 dés(w) C code: include include int dfs (int source ); int ab = 0, i jn, m, af 10}[10}, vis{10},source, num = 1; void main() { clrser(); printf ("\nEnter the Number of Vertices: ") scant ( "ed", &m printf ("\nEnter the Adjacency Matrix\n” ); for (i= Limit) for (j= 1) < scanf("%ed" &ali]liD: printf ("\nEnter the Starting Vertex: " ): seanf ( "fed", &source ); for (i= Lyi emits) visfi] dfs ( source ); if (ab==(n-1)) printf ( "Connected Graphin" ) else printf ("Unconnected Graph\n" ); getehQ; \VM.VINAYAKA jrnen. LECTURER, COMPUTER SCIENCI PAGE 39 DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, } int dfs (int source ) { vis[source] for (i= Thi <=mi+y if (alsource] [i] && visfi { ab +4: dis (i): } return 0; } OUTPUT 1: Enter the Number of Vertices:6 Enter the Adjacency Matrix 011010 101000 110100 oo1oil 100101 000110 Enter the Starting Vertex:1 Connected Graph OUTPUT 2: Enter the Number of Vertices:6 Enter the Adjacency Matrix 011000 101000 110000 000011 000101 000110 Enter the Starting Vertex:1 ‘Unconnected Graph \VIM.VINAYAKA erpeu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 40, 1, 22 33 44 55 66 Graph Traversal Sequence DFS with tree and back edges shown in solid and dotted lines respectively, Graph ‘Traversal Sequence DFS forest with tree and back edges ‘Shown in solid and dotted lines respectively 11 2235, 4152 65 \VIM.VINAYAKA rseu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 4) Java Code: import java.io.*; import java.util.*; class Graph { private int numVertices; private LinkedList adjLists[]; private boolean visited[]; Graph(int vertices) { adjLists = new LinkedList[vertices]; visited = new boolean|vertices]; for (int i = 0; i < vertices; i++) adjLists[i] = new LinkedList(); } void addEdge(int src, int dest) { adjLists[src].add(dest); } void DFS(int vertex) { visited[vertex] = true; System.out print(vertex + ""); Iterator ite = adjLists[vertex] listIterator(); while (ite.hasNext()) { int adj = ite.next(); if (1visitedfadj]) DFS(adj); } } public static void main(String args{]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); \VIM.VINAYAKA secu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 42, g.addEdge(2, 3); System.out println("Following is Depth First Traversal"); 2.DFS(2); } } OUTPUT: Following is Depth First Traversal 0; 12 2334 Graph Traversal Sequence DES with tree and back edges Shown in solid and dotted lines respectively DFS Concept explanation with example Let’s see how the Depth First Search algorithm works with an example. We use an undirected graph with 5 vertices. Visited Stack We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and putting all its adjacent vertices in the stack. LV M.VINAYAKA jrnen. LECTURER, COMPUTER SCIENCI PAGES DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, 0o Visited 1|2 3 Stack Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has already been visited, we visit 2 instead. oj1 Visited 2 3 Stack Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it. 0 }1 /2 Visited 4 a Stack \VIM.VINAYAKA seneu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 44 o/}1/2 /4 Visited 3 Stack After we visit the last element 3, it doesn’t have any unvisited adjacent nodes, so we have completed the Depth First Traversal of the graph. 0 |}1 |2 |4 | 3 | Visited Stack 8 Write a program to implement binary search using divide and conquer technique ALGORTIHM BinSearch(A[0 ...n-1], KEY) J Implements nonrecursive binay search / Input: An array A[0 ..n-1] sorted in ascending order and a search key KEY // Output: An index of the array’s element that is equal to KEY or -1 if there is no such element left © 0; right © n-1 while left <= right do middle € (left + right) /2 if KEY =A[middle] return middle else if KEY < A [middle] right € middle -1 else left € middle +1 return -1 Explanation of the concept:- Binary search or half-interval search or logarithmic search is an alogorithm used to search for an element (iter, In a sorted array in any order (ascending or descending) In this algorithm, several steps are to be performed as follows: \VIM.VINAYAKA secu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE AS Step 1 :Firstly the middle element of array is found and compared with the given item which user wante to search in an array. Step 2 :lf they are same then it will return the location of the required value. Step 3 :If they are not equal then it will break the array in half. Step 4 :If the middle element of array is smaller than the given item then it will search the first half of an array. StepS :If the middle element of array is greater than the given item then it will search the second half of a array ‘This process will continue until the given item is found oF until the loop terminates. C Code: include include define SIZE 10 int n; void main() { int A[SIZE], KEY J,flag; int BinSearch(int A[SIZE],int KEY); clrser(); printi("\nHow many elements in an array?"); seanf("%ed", en); printf("\nEnter the elements"); for (i=Orismiit+) scant("%ed" &ALiD); printi("Enter the element which is to be searched:"); scanf("‘hd",&KEY); flag=BinSearch(A,KEY); if flag==-1) print{("\nTPhe Element is not present"); printf("\nThe element is at A[%d] location’ fag); getch(); ) int BinSearch(int A[SIZE].int KEY) { int low,highm; m=(low+high)/2; if(KEY==Alm)) return m; else if (KEY Alm] Example: K= 70 Arrayitems=3, 14, 27, 31, 39, 42, 55, 70, 74, 81, 85, 93, 98. IndexvalueO 2 2 3 4 5 6 7 8 9 10 1 22 03 [14 [27 [31 [39 [42 [55 [70 [74 [a1 [85 [93 [98 Iteration TL ™ r Iteration 2 L m r Iteration 3 Lm Java Code: lass BinarySearchExample( public static void binarySearch(int arr, int first, int last int key){ int mid = (first + last)/2; while( first <= last ){ if (art{mid] < key )( first = mid + 1; \VIM.VINAYAKA yeneu, LECTURER, COMPUTER SCIENCE DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA PAGE 7 System,out println("Element is found at index: " + mid); break; jelse( last = mid - 1; d mid = (first + last)/2; } if (first > last ){ System.out printin(”Element is not found!"); } } public static void main(String args{)){ int anf] ={3, 14, 27, 31, 39, 42, 55, 70, 74, 81, 85, 93, 98}; int key = 70; int lastearr length-1; binarySearch(arr,0,last key); } } Output: Element is found at index: 7 9 Write a program to implement insertion sort using decrease and conquer technique ALGORITHM InsertionSort(A[0..0-1)) Sorts a given array by insertion sort Mnput: An array A[0,.n-1] of n orderable elements Output: Array A[0..n-1] sorted in increasing order Fori€1 to n-I do v€Alil iil while j>=0 and Alj]> v do Alj+1] © AG] ijl Alt] €v Explanation of the concept: - This sorting is generally used for small set of data. In this sorting, initially the first element is picked up in the unsorted part and is then appropriately inserted in the sorted part, this process will repeat till the final list in ordered accordingly. This is not a popular method of sorting with compare to selection sort and bubble sort In this algorithm, several steps are to be performed as follows: DEPARTMENT, RIS POLYTECHNIC, KORAMANGALA, \VM.VINAYAKA snes. LECTURER, COMPUTER SCIENCI PAGE 8

You might also like