cseexamhacks.files.wordpress.com …  · web viewprint all the nodes reachable from a given...

46
ANALSIS AND DESIGN OF ALGORITHM LAB BACHELOR OF TECHNOLOGY IN COMPUTER SCIENCE & ENGINEERING Amity of School of Engineering & Technology A mity University

Upload: vudang

Post on 04-Feb-2018

223 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

ANALSIS AND DESIGN OF ALGORITHM LAB

BACHELOR OF TECHNOLOGY IN COMPUTER SCIENCE & ENGINEERING

Amity of School of Engineering & Technology Amity University

UNDER THE GUIDANCE OF: SUBMITTED BY:

Page 2: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

INDEX

S.NO

CATEGORY OF EXP.

CODE Exp.No.

NAME OF EXPERIMENT DATE OF ALLOTMENT OF EXP.

DATE OFEVALUA

MAX.MARK

MARKSOBT.

SIGN.OFFACULTY

1. MANDATO-RYEXP.

LR (10)

1 Implement recursive binary search and linear search and determine the time required to search an element.

2. 2 Sort a given set of elements using heap sort method and determine the time required to sort the elements.

3. 3 Sort a given set of elements using merge sort method and determine the time required to sort the elements.

4. 4 Sort a given set of elements using selection sort method and determine the time required to sort the elements.

5.5

Implement 0/1 knapsack using dynamic programming

6. 6 From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm.

7 7 Sort a given set of elements using quick sort method and determine the time

Page 3: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n

8 8 Find the minimum cost spanning tree of a given undirected graph using Kruskal's algorithm.

9 9 Print all the nodes reachable from a given starting node in a digraph using BFS method.

10 10 Check whether a given graph is connected or not using DFS method.

11 11 Implement N Queens problem using back tracking

Viva Viva (5)

Page 4: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

EXPERIMENT – 1

1. OBJECTIVE: Implement recursive binary search and linear search and determine the time required to search an element. Repeat the experiment for different values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n.

2. EQUIPMENT / SOFTWARE USED:

3. THEORY:

In computer science, a binary search or half-interval search algorithm finds theposition of a specified input value (the search "key") within an array sorted by key value. For binary search, the array should be arranged in ascending or descending order. In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the subarray to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.A binary search halves the number of items to check with each iteration, so locating an item (ordetermining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquersearch algorithm.BINARY SEARCH

Class Search AlgorithmData Structure ArrayWorst Case Complexity O(log n)

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor Windows OS2. 16GB RAM Microsoft Word3. Keyboard g++ in Ubuntu(Linux).4. Mouse TURBO C5. Monitor6. Printer

Page 5: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

Best Case Complexity O(1)Average Case Complexity O(log n)

Linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched.[1]

Linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list. If each element is equally likely to be searched, then linear search has an average case of n/2 comparisons, but the average case can be affected if the search probabilities for each element vary. Linear search is rarely practical because other search algorithms and schemes, such as the binary search algorithm and hash tables, allow significantly faster searching for all but short lists

4. PROCEDURE:

1.

#include<iostream>using namespace std;int main(){int i, j, a[50], n, temp, beg, mid, end, item, flag = 1;double timecount;clock_t startclock, finishclock;cout<<"Enter size of the array : ";cin>>n;cout<<"Enter elements of the array : ";for(i = 0; i < n; i++){cin>>a[i];} cout<<"Sorted array is :";for(i = 0; i < n; i++){for(j = i+1; j < n; j++){if(a[i] > a[j]){temp = a[i];a[i] = a[j];a[j] = temp;}}}for(i = 0; i < n; i++){cout<<" "<<a[i];} cout<<"\nEnter the element to be searched : ";cin>>item;beg = 0;end = n - 1;startclock = clock();while(beg <= end){mid = (beg + end)/2;if(item == a[mid]){cout<<item<<" found at position "<<mid+1<<"\n";flag = 0;break;}

Page 6: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

else if(item >a[mid]){beg = mid + 1;} else{end = mid - 1;}}finishclock = clock();if(flag == 1){cout<<item<<" is not present in the array\n";} timecount = double (finishclock-startclock) /100;cout<<"Timecount : "<<timecount<<"\n";return 0;}

2.

#include <stdio.h>int main(){int array[100], search, c, n, count = 0;printf("Enter the number of elements in array\n");scanf("%d", &n);printf("Enter %d numbers\n", n);for ( c = 0 ; c < n ; c++ )scanf("%d", &array[c]);printf("Enter the number to search\n");scanf("%d", &search);for (c = 0; c < n; c++) { if (array[c] == search){printf("%d is present at location %d.\n", search, c+1);count++;} }if (count == 0)printf("%d is not present in array.\n", search);elseprintf("%d is present %d times in array.\n", search, count);return 0;}

5. OUTPUT:

1.

Page 7: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

2.

5. OBSERVATIONS AND DISCUSSIONS:

The output from the above code can be shown using above snapshot

6. RESULT:

The program is successfully written and created using C/C++ and g++ in Ubuntu(Linux)..

Faculty Name: Signature:Date:

Page 8: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

EXPERIMENT- 2

1. OBJECTIVE: Sort a given set of elements using heap sort method and determine the time required to sort the elements.

2. EQUIPMENT / SOFTWARE USED:

3. THEORY:

Heap Sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios. Heap sort algorithm is divided into two basic parts :

Creating a Heap of the unsorted list.

Then a sorted array is created by repeatedly removing the largest/smallest element from the

heap, and inserting it into the array. The heap is reconstructed after each removal.

4. PROCEDURE:

#include<stdio.h>#include<conio.h>int main()

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor Windows OS2. 16GB RAM Microsoft Word3. Keyboard Turbo C/C++4. Mouse SNIPPING TOOL5. Monitor6. Printer

Page 9: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

{int TREE[10],N,i,j,K,p,c,temp; printf("\n\n Enter no of elements.."); scanf("%d",&N); printf("\n\n Enter the nos..");for(i=1;i<=N;i++)scanf("%d",&TREE[i]);for(i=2;i<=N;i++){K=i;do{ if(TREE[K]>TREE[K/2]) {temp=TREE[K];TREE[K]=TREE[K/2];TREE[K/2]=temp;}p=K/2;K=p;}while(K!=0);}printf("\n\n\n On inserting values are arranged as \n");for(i=1;i<=N;i++) printf("%d\t",TREE[i]);for(j=N;j>0;j--){temp=TREE[1]; TREE[1]=TREE[j]; TREE[j]=temp; p=0;do{c=2*p+2;if((TREE[c][/c]<TREE[c language="+1"][/c]) && c<j-1)c++;if(TREE[p]<TREE[c][/c] && c<j){temp=TREE[p];TREE[p]=TREE[c][/c];TREE[c][/c]=temp;}p=c;}while(c<(j+1)); }printf("\n\n\n The sorted nos are..");for(i=1;i<=N;i++) printf("%d\t",TREE[i]);getch();}

5. OUTPUT:

Page 10: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

5. OBSERVATIONS AND DISCUSSIONS:

The output from the above code can be shown using above snapshot

6. RESULT:

The program is successfully written and created using C/C++..

Faculty Name: Signature:Date:

Page 11: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

EXPERIMENT – 3

1. OBJECTIVE: Sort a given set of elements using merge sort method and determine the time required to sort the elements.

2. EQUIPMENT / SOFTWARE USED:

4. THEORY:

Merge sort is a divide-and-conquer algorithm based on the idea of breaking down a list into several sub-lists until each sublist consists of a single element and merging those sublists in a manner that results into a sorted list.

Idea:

Divide the unsorted list into $$N$$ sublists, each containing $$1$$ element. Take adjacent pairs of two singleton lists and merge them to form a list of 2 elements. $

$N$$ will now convert into $$N/2$$ lists of size 2.

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor SNIPPING TOOL2. 16GB RAM Microsoft Word3. Keyboard4. Mouse5. Monitor6. Printer

Page 12: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

Repeat the process till a single sorted list of obtained.

While comparing two sublists for merging, the first element of both lists is taken into consideration. While sorting in ascending order, the element that is of a lesser value becomes a new element of the sorted list. This procedure is repeated until both the smaller sublists are empty and the new combined sublist comprises all the elements of both the sublists

5 PROCEDURE :

#include<stdio.h>void mergesort(int a[],int i,int j);void merge(int a[],int i1,int j1,int i2,int j2);int main(){int a[30],n,i; printf("Enter no of elements:"); scanf("%d",&n); printf("Enter array elements:"); for(i=0;i<n;i++) scanf("%d",&a[i]); mergesort(a,0,n-1); printf("\nSorted array is :"); for(i=0;i<n;i++) printf("%d ",a[i]); return 0;}void mergesort(int a[],int i,int j){ int mid; if(i<j) { mid=(i+j)/2;  mergesort(a,i,mid);          mergesort(a,mid+1,j);    merge(a,i,mid,mid+1,j);     }}void merge(int a[],int i1,int j1,int i2,int j2)

{int temp[50];        int i,j,k;    i=i1;        j=i2;       k=0; while(i<=j1 && j<=j2)    //while elements in both lists    { if(a[i]<a[j])            temp[k++]=a[i++];        else            temp[k++]=a[j++];   }    while(i<=j1)            temp[k++]=a[i++];    while(j<=j2)            temp[k++]=a[j++];    for(i=i1,j=0;i<=j2;i++,j++)        a[i]=temp[j];}

Page 13: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

5. OUTPUT:

5.

OBSERVATIONS AND DISCUSSIONS:

The output from the above code can be shown using above snapshot

6. RESULT:

The program is successfully written and created using C/C++.

Faculty Name: Signature:Date:

Page 14: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

EXPERIMENT – 4

1.OBJECTIVE: Sort a given set of elements using selection sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n

2. EQUIPMENT / SOFTWARE USED:

3. THEORY:

Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor TURBO C++2. 16GB RAM Microsoft Word3. Keyboard SNIPPING TOOL4. Mouse5. Monitor6. Printer

Page 15: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.

This algorithm is not suitable for large data sets as its average and worst case complexities are of Ο(n2), where n is the number of items.

4. PROCEDURE:

#include <stdio.h>int *selectionSort(int array[],int n){int j,temp,i;for (i = 0; i < n; i++){for(j = i+1; j < n; j++){if(array[i] > array[j]){temp = array[i]; array[i] = array[j];array[j] = temp; } } }return array;}int main(){ int array[1000],n,i;printf("Enter the number of element you want to Sort : ");scanf("%d",&n);printf("Enter Elements in the list : ");for(i = 0; i < n; i++){scanf("%d",&array[i]);}int *sortArray = selectionSort(array,n); printf("Sorted list : ");for(i = 0; i < n; i++ ){printf("%d\t",sortArray[i]); }}

5. OUTPUT:

Page 16: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

6. OBSERVATIONS AND DISCUSSIONS:The output from the above code can be shown using above snapshot

7. RESULT:The program is successfully written and created using C/C++.

Faculty Name: Signature:Date:

EXPERIMENT – 5

1.OBJECTIVE: Implement 0/1 knapsack using dynamic programming

2. EQUIPMENT / SOFTWARE USED:

3. THEORY:Given weights and values of n items, put these items in a knapsack of capacity W toget the maximum total value in the knapsack. In other words, given two integer arrays val[0 … n-1] and wt[0 … n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor g++ in Ubuntu(Linux).2. 16GB RAM Microsoft Word3. Keyboard SNIPPING TOOL4. Mouse5. Monitor6. Printer

Page 17: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break item, either pick the complete item, or don't pick it (0/1 property).A simple solution is to consider all subsets of items and calculate the total weight and value of allsubsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the maximum value subset.

Optimal Substructure:To consider all subsets of items, there can be two cases for every item –1. The item is included in the optimal subset.2. The item is not included in the optimal set.

Therefore, the maximum value that can be obtained from n items is max of following two values –1. Maximum value obtained by n-1 items and W weight (excluding nth item).2. Value of nth item plus maximum value obtained by n-1 items and W minus weight of the nthitem (including nth item). If weight of nth item is greater than W, then the nth item cannot be included and case 1 is the only possibility.

Overlapping Subproblems:Since subproblems are evaluated again, this problem has Overlapping Subproblems property. So the 0/1 Knapsack problem has both properties of a dynamic programming problem. Like other typical Dynamic Programming problems, re-computations of same subproblems can be avoided by constructing a temporary array K[][] in bottom up manner. Following is Dynamic Programming based implementation.

4. PROCEDURE:

#include<iostream>using namespace std;int main(){int w[10], v[10], W, n, i, c[10][30], u, k;cout<<"Enter capacity of Knapsack : ";cin>>W;cout<<"Enter number of items : ";cin>>n;cout<<"Enter the weight of items : ";for(i = 1; i <= n; i++){cin>>w[i];} cout<<"Enter the value of items :";for(i = 1; i <= n; i++){cin>>v[i];} cout<<"Weight array is :";for(i = 1; i <= n; i++){cout<<w[i]<<" ";}cout<<"\nValue array is : ";for(i = 1; i <= n; i++)

Page 18: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

{cout<<v[i]<<" ";}for(u = 0; u <= W; u++){c[0][u] = 0;}for(i = 0; i <= n; i++){c[i][0] = 0;}for(i = 1; i <= n; i++){for(u = 1; u <= W; u++){if(w[i] <= u){if(v[i] + c[i-1][u-w[i]] > c[i-1][u]){c[i][u] = v[i] + c[i-1][u-w[i]];} else{c[i][u] = c[i-1][u];}} else{c[i][u] = c[i-1][u];}}}cout<<"\nWeight-value (cost) matrix : \n";for(i = 0; i <= n; i++){for(u = 0; u <= W; u++){cout<<c[i][u]<<" ";} cout<<"\n";} cout<<"Maximum value of items included in Knapsack ="<<c[n][W]<<"\n";i = n;k = W;cout<<"Items in Knapsack are : ";while(i > 0 && k > 0){if(c[i][k] != c[i-1][k]){cout<<i<<" ";k = k - w[i];}i= i - 1;} cout<<"\n";return 0;}

5. OUTPUT

Page 19: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

6. OBSERVATIONS AND DISCUSSIONS:

The output from the above code can be shown using above snapshot

7. RESULT:The program is successfully written and created using g++ in Ubuntu(Linux).

Faculty Name: Signature:Date:

EXPERIMENT – 6

1.OBJECTIVE: From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm

2. EQUIPMENT / SOFTWARE USED:

3. THEORY:

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor TURBO C++2. 16GB RAM Microsoft Word3. Keyboard SNIPPING TOOL4. Mouse5. Monitor6. Printer

Page 20: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959,[1][2] is a graph search algorithm that solves the single-source shortest path problem for a graph with nonnegative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms.For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined.For example, if the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably IS-IS and OSPF (Open Shortest Path First).

4. PROCEDURE:

#include<stdio.h>#include<conio.h>#include<process.h>#include<string.h>#include<math.h>int dijkstra(int cost[][N],int source,int target);void main() {int cost[N][N],i,j,w,ch,co;int source,target,x,y;clrscr();printf("Shortest path algorithm DIJKSTRA'S ALGORITHM \n\n");for(i=1;i<N;i++){for(j=1;j<N;j++){cost[i][j]=IN;}}for(x=1;x<N;x++){for(y=x+1;y<N;y++){printf("Enter the weight of the path between node %d and %d:",x,y); scanf("%d",&w);cost[x][y]=cost[y][x]=w;}printf("\n");}printf("\n Enter the source:"); scanf("%d",&source); printf("\n Enter the target"); scanf("%d",&target); co=dijsktra(cost,source,target); printf("\n shortest path:%d",co); getch();}int dijsktra(int cost[][N],int source,int target){int dist[N],prev[N],selected[N]={0},i,m,min,start,d,j; char path[N];for(i=1;i<N;i++){dist[i]=IN; prev[i]=-1;}start=source;selected[start]=1;dist[start]=0;while(selected[target]==0){min=IN;m=0;for(i=1;i<N;i++){d=dist[start]+cost[start][i]; if(d<dist[i] && selected[i]==0)

Page 21: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

{dist[i]=d;prev[i]=start;}if(min>dist[i] && selected[i]==0){min=dist[i];m=i;}}start=m;selected[start]=1;}start=target;j=0; while(start!=-1){path[j++]=start+65;start=prev[start];}path[j]='\0';strrev(path);printf("%s",path);return dist[target];}

5. OUTPUT:

6. OBSERVATIONS AND DISCUSSIONS:The output from the above code can be shown using above snapshot

Page 22: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

7. RESULT:

The program is successfully written and created using C/C++.

Faculty Name: Signature:Date:

EXPERIMENT – 7

1. OBJECTIVE: Sort a given set of elements using quick sort method and determine the time required to sort the elements.

2. EQUIPMENT / SOFTWARE USED:

3. THEORY:

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor Windows OS2. 16GB RAM Microsoft Word3. Keyboard G++ in UBUNTU (Linux)4. Mouse SNIPPING TOOL5. Monitor6. Printer

Page 23: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

Quick sort (sometimes called partition-exchange sort) is an efficient sorting algorithm,serving as a systematic method for placing the elements of an array in order. Developed by TonyHoare in 1960, it is still a very commonly used algorithm for sorting. When implemented well, itcan be about two or three times faster than its main competitors, merge sort and heap sort.Quick sort is a comparison sort, meaning that it can sort items of any type for which a "less-than"relation (formally, a total order) is defined. In efficient implementations it is not a stable sort,meaning that the relative order of equal sort items is not preserved. Quick sort can operate in-place on an array, requiring small additional amounts of memory to perform the sorting.Mathematical analysis of quick sort shows that, on average, the algorithm takes O(n log n)comparisons to sort n items. In the worst, it makes O(n2) comparisons, though this behavior is rare Quick sort is a divide and conquer algorithm. Quick sort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quick sort can then recursively sort the subarrays.The steps are –1. Pick an element, called a pivot, from the array.2. Reorder the array so that all elements with values less than the pivot come before the pivot,while all elements with values greater than the pivot come after it (equal values can go eitherway). After this partitioning, the pivot is in its final position. This is called the partitionoperation.Recursively apply the above steps to the sub-array of elements with smaller values and separately tothe sub-array of elements with greater values.4. PROCEDURE:

#include<iostream>using namespace std;int a[10], l, u, i, j, n, count = 0;double timecount;clock_t startclock, finishclock;void quick(int*, int, int);int main(){double timecount;clock_t startclock, finishclock;cout<<"Ener size of the array : ";cin>>n;cout<<"Enter elements of the array : ";for(i = 0; i < n; i++){cin>>a[i];} u = n-1;startclock = clock();quick(a, l, u);finishclock = clock();cout<<"Sorted array is :";for(i = 0; i < n; i++){cout<<" "<<a[i];} cout<<"\n";timecount = double (finishclock-startclock) / 100;cout<<"Timecount : "<<timecount<<"\n";

Page 24: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

return 0;}void quick(int a[], int l, int u){int p, temp;if(l < u){p = a[l];i = l;j = u;while(i < j){while(a[i] <= p && i < j){i++;}while(a[j] > p && i <= j){j--;} if(i<= j){temp = a[i];a[i] = a[j];a[j] = temp;}} temp =a[j];a[j] = a[l];a[l] = temp;cout<<"Iteration "<<count+1<<" :";count++;for(i = 0; i < n; i++){cout<<" "<<a[i];} cout<<"\n";quick(a, l, j-1);quick(a, j+1, u);}}5. OUTPUT:

6. OBSERVATIONS AND DISCUSSIONS:

The output from the above code can be shown using above snapshot

Page 25: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

7. RESULT:

The program is successfully written and created using g++ in Ubuntu(Linux).

Faculty Name: Signature:Date:

EXPERIMENT – 8

1.OBJECTIVE: Find the minimum cost spanning tree of a given undirected graph using Kruskal's algorithm

2. EQUIPMENT / SOFTWARE USED:

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor Windows OS2. 16GB RAM Microsoft Word3. Keyboard TUBO C4. Mouse SNIPPING TOOL5. Monitor6. Printer

Page 26: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

3. THEORY:Kruskal's algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree for a connected weighted graph. It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.This algorithm is directly based on the MST( minimum spanning tree) property.

4. PROCEDURE:

#include<stdio.h>#include<conio.h>#include<stdlib.h>int i,j,k,a,b,u,v,n,ne=1;int min,mincost=0,cost[9][9],parent[9];int find(int);int uni(int,int);void main(){clrscr();printf("\n\tImplementation of Kruskal's algorithm\n");printf("\nEnter the no. of vertices:");scanf("%d",&n);printf("\nEnter the cost adjacency matrix:\n");for(i=1;i<=n;i++){for(j=1;j<=n;j++){scanf("%d",&cost[i][j]);if(cost[i][j]==0)cost[i][j]=999;}}printf("The edges of Minimum Cost Spanning Tree are\n");while(ne < n){for(i=1,min=999;i<=n;i++){for(j=1;j <= n;j++){if(cost[i][j] < min){min=cost[i][j];a=u=i;b=v=j;}}}u=find(u);v=find(v);if(uni(u,v)){printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);mincost +=min;}cost[a][b]=cost[b][a]=999;}printf("\n\tMinimum cost = %d\n",mincost);getch();}int find(int i){while(parent[i])i=parent[i];return i;}int uni(int i,int j)

Page 27: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

{if(i!=j){parent[j]=i;return 1;}return 0;}

5. OUTPUT:

6. OBSERVATIONS AND DISCUSSIONS:

The output from the above code can be shown using above snapshot

7. RESULT:

The program is successfully written and created using c.

Faculty Name: Signature:Date:

Page 28: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

EXPERIMENT – 9

1.OBJECTIVE : Print all the nodes reachable from a given starting node in a digraph using BFS method.

2. EQUIPMENT / SOFTWARE USED:

3. THEORY:Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor Windows OS2. 16GB RAM Microsoft Word3. Keyboard g++ in Ubuntu(Linux).4. Mouse SNIPPING TOOL5. Monitor6. Printer

Page 29: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred toas a 'search key'[1]) and explores the neighbor nodes first, before moving to the next levelneighbors.This is a very different approach for traversing the graph nodes. The aim of BFS algorithm isto traverse the graph as close as possible to the root node. Queue is used in theimplementation of the breadth first search.Step 1: Push the root node in the Queue.Step 2: Loop until the queue is empty.Step 3: Remove the node from the Queue.Step 4: If the removed node has unvisited child nodes, mark them as visited and insert theunvisited children in the queue.

4. PROCEDURE:#include<iostream>using namespace std;int c = 0, t = 0;struct node_info{int no;int st_time;}*q = NULL, *r = NULL, *x = NULL;struct node{node_info *pt;node *next;}*front = NULL, *rear = NULL, *p = NULL, *np = NULL;void push(node_info *ptr){np = new node;np->pt = ptr;np->next = NULL;if(front == NULL){front = rear = np;rear->next = NULL;13} else{rear->next = np;rear = np;rear->next = NULL;}}node_info *remove(){if(front == NULL){cout<<"Empty queue\n";} else{p = front;x = p->pt;front = front->next;delete(p);return(x);}}void bfs(int *v,int am[][10],int i, int n)

Page 30: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

{if(c == 0){q = new node_info;q->no = i;q->st_time = t++;cout<<"At number "<<q->st_time+1<<", node "<<q->no+1<<" is traversed\n";v[i] = 1;push(q);} c++;for(int j = 0; j < n; j++){if(am[i][j] == 0 || (am[i][j] == 1 && v[j] == 1))continue;else if(am[i][j] == 1 && v[j] == 0){r = new node_info;r->no = j;r->st_time = t++;cout<<"At number "<<r->st_time+1<<", node "<<r->no+1<<" istraversed\n";v[j] = 1;push(r);}}remove();if(c <= n-1 && front != NULL){bfs(v, am, remove()->no, n);}}int main(){int i, j, n, v[10], am[10][10];cout<<"Enter number of nodes in graph : ";cin>>n;for(i = 0; i < n; i++){v[i] = 0;}for(i = 0; i < n; i++){cout<<"Enter the adjacency matrix for node "<<i+1<<" : ";for(j = 0; j < n; j++){cin>>am[i][j];}}bfs(v, am, 0, n);return 0;} 5. OUTPUT:

Page 31: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

6. OBSERVATIONS AND DISCUSSIONS:The output from the above code can be shown using above snapshot

7. RESULT:

The program is successfully written and created using g++ in Ubuntu(Linux)

Faculty Name: Signature:Date:

EXPERIMENT – 10

Page 32: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

1. OBJECTIVE: Check whether a given graph is

connected or not using DFS method.

2. EQUIPMENT/SOFTWARE USED:

THEORY:

Depth-first search (DFS) is an algorithm for traversing or searching tree or graph datastructures. One starts at the root (selecting some arbitrary node as the root in the case of agraph) and explores as far as possible along each branch before backtracking.The aim of DFS algorithm is to traverse the graph in such a way that it tries to go far from theroot node. Stack is used in the implementation of the depth first search.Step 1: Push the root node in the Stack.Step 2: Loop until stack is empty.Step 3: Peek the node of the stack.Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it astraversed and push it on stack.

3. Step 5: If the node does not have any unvisited child nodes, pop the node from the stack.

4.PROCEDURE:

#include<iostream.h>#include<conio.h>#include<stdlib.h>int cost[10][10],i,j,k,n,stack[10],top,v,visit[10],visited[10];void main(){ int m;cout <<"enter no of vertices";cin >> n;cout <<"enter no of edges";cin >> m;cout <<"\n EDGES \n";

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor Windows OS2. 16GB RAM Microsoft Word3. Keyboard TURBO C4. Mouse SNIPPING TOOL5. Monitor6. Printer

Page 33: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

for(k=1;k<=m;k++){ cin >>i>>j;cost[i][j]=1;}cout <<"enter initial vertex";cin >>v;cout <<"ORDER OF VISITED VERTICES";cout << v <<" ";visited[v]=1;k=1;while(k<n){for(j=n;j>=1;j--)if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1){visit[j]=1;stack [top]=j;top++;}v= stack [--top];cout<<v << " ";k++;visit[v]=0;visited[v]=1;}getch();}

5. OUTPUT

6. OBSERVATIONS AND DISCUSSIONS:

Page 34: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

The output from the above code can be shown using above snapshot

7. RESULT:The program is successfully written and created using C/C++.

Faculty Name: Signature:Date

EXPERIMENT – 11

Page 35: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

1. OBJECTIVE: Implement N Queens problem using back tracking.

2. EQUIPMENT/SOFTWARE USED:

3. THEORY: The EIGHT QUEENS PUZZLE is the problem of placing eight chess queens on an 8×8chessboard so that no two queens threaten each other. Thus, a solution requires that no twoqueens share the same row, column, or diagonal. The eight queens puzzle is an example ofthe more general n-queens problem of placing n queens on an n×n chessboard, wheresolutions exist for all natural numbers n with the exception of n=2 and n=3.[Initialize x array to zero and start by placing the first queen in k=1 in the first row.To find the column position start from value 1 to n, where ‗n‘ is the no. Of columns or no. Ofqueens.If k=1 then x (k)=1.so (k,x(k)) will give the position of the k th queen. Here we have to checkwhether there is any queen in the same column or diagonal.For this considers the previous position, which had already, been found out. Check whetherX (I)=X(k) for column |X(i)-X(k)|=(I-k) for the same diagonal.If any one of the conditions is true then return false indicating that k th queen can‘t be placedin position X (k).For not possible condition increment X (k) value by one and precede d until the position isfound.If the position X (k) n and k=n then the solution is generated completely.If k<n, then increment the ‗k‘ value and find position of the next queen.If the position X (k)>n then k th queen cannot be placed as the size of the matrix is ‗N*N‘.So decrement the ‗k‘ value by one i.e. we have to back track and after the position of theprevious queen.

4. PROCEDURE: #include<stdio.h>

Name:Enrollment no:Date:

S.No. Hardware Software1. I7 Processor Windows OS2. 16GB RAM Microsoft Word3. Keyboard TURBO C++4. Mouse SNIPPING TOOL5. Monitor6. Printer

Page 36: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

#include<conio.h>#include<math.h>char a[10][10];int n;void printmatrix(){int i,j;printf("n");for(i=0;i < n;i++){for(j=0;j < n;j++)printf("%ct",a[i][j]);printf("nn");}}int getmarkedcol(int row){int i,j;for(i=0;i < n;i++)if(a[row][i]=='Q'){return(i);break;}}int feasible(int row, int col){int i,tcol;for(i=0;i < n;i++){tcol=getmarkedcol(i);if(col==tcol || abs(row-i)==abs(col-tcol))return 0;}return 1;}void nqueen(int row){int i,j;if(row < n){for(i=0;i < n;i++){if(feasible(row,i)){a[row][i]='Q';nqueen(row+1);a[row][i]='.';}}}else{printf("nThe solution is:- ");printmatrix();}}void main(){int i,j;clrscr();printf("n Enter the no. of queens:- ");scanf("%d",&n);for(i=0;i < n;i++)for(j=0;j < n;j++)a[i][j]='.';nqueen(0);getch();}

Page 37: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of

5. OUTPUT

6. OBSERVATIONS AND DISCUSSIONS:The output from the above code can be shown using above snapshot

7. RESULT:The program is successfully written and created using C/C++.

Faculty Name: Signature:Date

Page 38: cseexamhacks.files.wordpress.com …  · Web viewPrint all the nodes reachable from a given starting node in a digraph using ... find out the maximum value ... is the problem of