ALGORITHMS LAB MANUAL - Updated
ALGORITHMS LAB MANUAL - Updated
PAGE FACULTY
S.NO DATE TITLE MARKS
NO. SIGN
SEARCHING AND SORTING ALGORITHMS
AIM:
To implement Linear Search and Determine the time required to search for 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.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main()
{
int array[50],i,target,num;
printf("How many elements do you want in the array");
scanf("%d",&num);
printf("Enter array elements:");
for(i=0;i<num;++i)
scanf("%d",&array[i]);
printf("Enter element to search:");
scanf("%d",&target);
for(i=0;i<num;++i)
if(array[i]==target)
break;
if(i<num)
printf("Target element found at location %d",i);
else
printf("Target element not found in an array");
return 0;
}
1
OUTPUT:
RESULT:
Thus the C program for implementation of Linear search algorithm was done and executed
successfully.
2
EX.NO:2 BINARY SEARCH
DATE:
AIM:
To implement recursive Binary Search. 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.
ALGORITHM:
PROGRAM:
#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elements");
scanf("%d",&n);
printf("Enter %d integers", n);
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to find");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high) {
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key) {
printf("%d found at location %d", key, mid+1);
break;
}
3
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list", key);
return 0;
}
OUTPUT:
RESULT:
Thus the C program for implementation of Binary search algorithm was done and executed
successfully.
4
EX.NO: 3 STRING MATCHING ALGORITHM
DATE:
AIM:
To write a function search (char pat [ ], char txt [ ]) that prints all occurrences of pat [ ] in
txt [ ] for given a text txt [0...n-1] and a pattern pat [0...m-1],. You may assume that n > m.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int match(char st[100], char pat[100]);
int main(int argc, char **argv) {
char st[100], pat[100];
int status;
printf("*** Naive String Matching Algorithm ***\n");
printf("Enter the String.\n");
gets(st);
printf("Enter the pattern to match.\n");
gets(pat);
status = match(st, pat);
if (status == -1)
printf("\nNo match found");
ese
printf("Match has been found on %d position.", status);
return 0;
}
int match(char st[100], char pat[100]) {
int n, m, i, j, count = 0, temp = 0;
n = strlen(st);
m = strlen(pat);
for (i = 0; i <= n - m; i++) {
5
temp++;
for (j = 0; j < m; j++) {
if (st[i + j] == pat[j])
count++;
}
if (count == m)
return temp;
count = 0;
}
return -1;
}
OUTPUT:
Enter the String. [email protected]
Enter the pattern to match. Dharm
RESULT:
Thus, the C program for implementation of String pattern matching algorithm was
done and executed successfully.
6
EX.NO:4.a INSERTION SORT
DATE:
AIM:
To Sort a given set of elements using the Insertion sort methods 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.
ALGORITHM:
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step2 - Pick the next element, and store it separately in a key.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to the
next element. Else, shift greater elements in the array towards the right.
Step 5 - Insert the value.
Step 6 - Repeat until the array is sorted.
PROGRAM:
#include <stdio.h>
void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one positio
n ahead from their current position*/
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}
7
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}
OUTPUT:
RESULT:
Thus the program for Insertion sort has been implemented and executed successfully
8
EX.NO:4.b HEAP SORT
DATE:
AIM:
To Sort a given set of elements using the Heap sort methods 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.
ALGORITHM:
Step 1: HeapSort(arr)
Step 2: BuildMaxHeap(arr)
Step 3: for i = length(arr) to 2
Step 4: swap arr[1] with arr[i]
Step 5: heap_size[arr] = heap_size[arr] ? 1
Step 6 : MaxHeapify(arr,1)
End
BuildMaxHeap(arr)
1. BuildMaxHeap(arr)
2. heap_size(arr) = length(arr)
3. for i = length(arr)/2 to 1
4. MaxHeapify(arr,i)
5. End
MaxHeapify(arr,i)
1. MaxHeapify(arr,i)
2. L = left(i)
3. R = right(i)
4. if L? heap_size[arr] and arr[L] > arr[i]
5. largest = L
6. else
7. largest = i
8. if R? heap_size[arr] and arr[R] > arr[largest]
9. largest = R
10. if largest != i
11. swap arr[i] with arr[largest]
12. MaxHeapify(arr,largest)
13. End
9
PROGRAM:
#include <stdio.h>
void heapify(int a[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child
int right = 2 * i + 2; // right child
if (left < n && a[left] > a[largest])
largest = left;
if (right < n && a[right] > a[largest])
largest = right;
if (largest != i) {
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
heapify(a, n, largest);
}
}
10
int main()
{
int a[] = {48, 10, 23, 43, 28, 26, 1};
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
heapSort(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}
OUTPUT:
RESULT:
Thus, the program for Heap sort method has been implemented and executed
successfully.
11
GRAPH ALGORITHMS
AIM:
ALGORITHM:
PROGRAM
#include <stdio.h>
int n, i, j, visited[10], queue[10], front = -1, rear = -1;
int adj[10][10];
void bfs(int v)
{
for (i = 1; i <= n; i++)
if (adj[v][i] && !visited[i])
queue[++rear] = i;
if (front <= rear)
{
visited[queue[front]] = 1;
bfs(queue[front++]);
}
}
void main()
{
int v;
printf("Enter the number of vertices: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
queue[i] = 0;
visited[i] = 0;
}
printf("Enter graph data in matrix form: \n");
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
12
scanf("%d", &adj[i][j]);
printf("Enter the starting vertex: ");
scanf("%d", &v);
bfs(v);
printf("The node which are reachable are: \n");
for (i = 1; i <= n; i++)
if (visited[i])
printf("%d\t", i);
else
printf("BFS is not possible. Not all nodes are reachable");
return 0;
}
OUTPUT:
Enter the number of vertices: 4
Enter graph data in matrix form:
0110
1001
1001
0110
Enter the starting vertex: 2
The node which are reachable are:
1 2 3 4
RESULT:
Thus, the program for Breadth first search algorithm has been implemented and
executed successfully.
13
EX.NO:2 DEPTH FIRST SEARCH
DATE:
AIM:
ALGORITHM:
Step 1: Create a stack with the total number of vertices in the graph as the size.
Step 2: Choose any vertex as the traversal's beginning point. Push a visit to that vertex and
add it to the stack.
Step 3 - Push any non-visited adjacent vertices of a vertex at the top of the stack to the top of
the stack.
Step 4 - Repeat steps 3 and 4 until there are no more vertices to visit from the vertex at the
top of the stack.
Step 5 - If there are no new vertices to visit, go back and pop one from the stack using
backtracking.
Step 6 - Continue using steps 3, 4, and 5 until the stack is empty.
Step 7 - When the stack is entirely unoccupied, create the final spanning tree by deleting the
graph's unused edges.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
/* ADJACENCY MATRIX */
int source,V,E,time,visited[20],G[20][20];
void DFS(int i)
{
int j;
visited[i]=1;
printf(" %d->",i+1);
for(j=0;j<V;j++)
{
if(G[i][j]==1&&visited[j]==0)
DFS(j);
}
}
int main()
{
int i,j,v1,v2;
printf("\t\t\tGraphs\n");
printf("Enter the no of edges:");
scanf("%d",&E);
14
printf("Enter the no of vertices:");
scanf("%d",&V);
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
G[i][j]=0;
}
/* creating edges :P */
for(i=0;i<E;i++)
{
printf("Enter the edges (format: V1 V2) : ");
scanf("%d%d",&v1,&v2);
G[v1-1][v2-1]=1;
for(i=0;i<V;i++)
{
for(j=0;j<V;j++)
printf(" %d ",G[i][j]);
printf("\n");
}
printf("Enter the source: ");
scanf("%d",&source);
DFS(source-1);
return 0;
}
15
OUTPUT:
RESULT:
Thus, the program for Depth first search algorithm has been implemented and
executed successfully.
16
EX.NO:3 DIJKSTRA’S ALGORITHM
DATE:
AIM:
To develop a program to find the shortest paths from a given vertex in a weighted
connected graph to other vertices using Dijkstra’s algorithm.
ALGORITHM:
Step 1: Create a set S that keeps track of vertices included in shortest path tree, i.e.,
whose minimum distance from source is calculated and finalized. Initially, this set is
empty.
Step 2: Assign a distance value to all vertices in the input graph. Initialize all distance
values as INFINITE and Assign distance value as 0 for the source vertex so that it is
picked first.
Step 3: While S doesn’t include all vertices
Pick a Vertex u which is not there in S and has minimum distance value.
Include u to S.
Update distance value of all adjacent vertices of u.
Step 4: To update the distance values, iterate through all adjacent vertices. For every adjacent
vertex v, ifsum of distance value of u (from source) and weight of edge u-v, is less than the
distance value of v, then update the distance value of v.
PROGRAM:
#include<stdio.h>
#define infinity 999
void dij(int n, int v,int cost[20][20], int dist[])
{
int i,u,count,w,flag[20],min;
for(i=1;i<=n;i++)
flag[i]=0, dist[i]=cost[v][i];
count=2;
while(count<=n){
min=99;
for(w=1;w<=n;w++)
if(dist[w]<min && !flag[w])
{
flag[u]=1;count++;
for(w=1;w<=n;w++)
if((dist[u]+cost[u][w]<dist[w]) && !flag[w])
dist[w]=dist[u]+cost[u][w];
17
}
min=dist[w];
u=w;
}
}
int main(){
int n,v,i,j,cost[20][20],dist[20];
printf("enter the number of nodes:");
scanf("%d",&n);
printf("\n enter the cost 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]=infinity;
}
printf("\n enter the source matrix:");
scanf("%d",&v);
dij(n,v,cost,dist);
printf("\n shortest path : \n");
for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d,cost=%d\n",v,i,dist[i]);
}
18
OUTPUT:
RESULT:
Thus, the program for finding shortest path using Dijkstra’s algorithm has been
implemented and executed successfully.
19
EX.NO:4 MINIMUM COST SPANNING TREE
DATE:
AIM:
To develop a program to find the minimum cost spanning tree of a given undirected graph
using Prim’s algorithm.
ALGORITHM:
Step 1: Create a set Sthat keeps track of vertices already included in MST.
Step 2: Assign a key value to all vertices in the input graph. Initialize all key values as
INFINITE.Assign key value as 0 for the first vertex so that it is picked first.
Step 3: While S doesn’t include all vertices.
Pick a vertex u which is not there in Sand has minimum key value.
Include u to S.
Update key value of all adjacent vertices of u.
To update the key values, iterate through all adjacent vertices. For every adjacent vertex v, if
weight of edge u-v is less than the previous key value of v, update the key value as weight of
u-v
The idea of using key values is to pick the minimum weight edge from cut. The key values
are usedonly for vertices which are not yet included in MST, the key value for these vertices
indicate the minimum weight edges connecting them to the set of vertices included in MST.
PROGRAM:
#include<stdio.h>
inta,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];void main()
{
printf("\n Enter the number ofnodes:"); scanf("%d",&n);
printf("\n Enter the 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;
}
visited[1]=1;
printf("\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
20
b=v=j;
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
}
21
OUTPUT:
RESULT:
Thus, the program for finding shortest path using Prim’s algorithm has been
implemented and executed successfully.
22
EX.NO:5 ALL-PAIRS- SHORTEST-PATHS PROBLEM
DATE :
AIM:
ALGORITHM:
Step 1: Initialize the solution matrix same as the input graph matrix as a first step. Then
we update the solution matrix by considering all vertices as an intermediate vertex. The
ideas is to one by one pick all vertices and update all shortest paths which include the
picked vertex as an intermediate vertex in the shortest path.
Step 2: When we pick vertex number k as an intermediate vertex, we already have considered
vertices {0, 1, 2, .. k-1} as intermediate vertices.
Step 3: For everypair (i, j) of source and destination vertices respectively, there are two possible
cases.
k is not an intermediate vertex in shortest path from i to j. We keep the value of
dist[i][j] as it is.
k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j]
asdist[i][k] + dist[k][j].
PROGRAM:
#include<stdio.h
>int
min(int,int);
void floyds(int p[10][10],int n)
{
Int i,j,k; for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j)
p[i][j]=0;
else
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
int min(inta,int b){
if(a<b)
return(a);
else
return(b);
}
main(){
int p[10][10],w,n,e,u,v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:\n");
23
scanf("%d",&e);
for(i=1;i<=n;i++){
for(j=1;j<=n;j++)
p[i][j]=999;
}
for(i=1;i<=e;i++){
printf("\n Enter the end vertices of edge%d with its weight \n",i);
scanf("%d%d%d",&u,&v,&w);
p[u][v]=w;
}
printf("\n Matrix of input data:\n");
for(i=1;i<=n;i++) {
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
floyds(p,n);
printf("\n Transitive closure:\n");
for(i=1;i<=n;i++){
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
printf("\n The shortest paths are:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
printf("\n <%d,%d>=%d",i,j,p[i][j]);
}
}
24
OUTPUT:
RESULT:
Thus, the program for finding All-Pairs- Shortest-Paths using Floyd’s algorithm
hasbeen implemented and executed successfully.
25
EX.NO:6 WARSHALL'S ALGORITHM
DATE:
AIM:
To implement program for transitive closure of a given directed graph using
Warshall's algorithm.
ALGORITHM:
PROGRAM:
#include <stdio.h>
int n,a[10][10],p[10][10];
void path()
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
p[i][j]=a[i][j];
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1)p[i][j]=1;
}
void main()
{
int i,j;
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
path();
26
printf("\nThe path matrix is shown below\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++)
printf("%d ",p[i][j]);printf("\n");
}
}
OUTPUT:
RESULT:
Thus, the program for finding All-Pairs- Shortest-Paths using Floyd’s algorithm
hasbeen implemented and executed successfully.
27
ALGORITHM DESIGN TECHNIQUES
AIM:
To develop a program to find out the maximum and minimum numbers in a given list
of n numbers using the divide and conquer technique.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<stdio.h>
int max, min;
int a[100];
void maxmin(int i, int j)
{
int max1, min1, mid;
if(i==j)
{
max = min = a[i];
}
else
{
if(i == j-1)
{
if(a[i] <a[j])
{
max = a[j];
min = a[i];
}
else
{
max = a[i];
min = a[j];
28
}
}
else
{
mid = (i+j)/2;
maxmin(i, mid);
max1 = max; min1 = min;
maxmin(mid+1, j);
if(max <max1)
max = max1;
if(min > min1)
min = min1;
}
}
}
int main ()
{
int i, num;
printf ("\nEnter the total number of numbers : ");
scanf ("%d",&num);
printf ("Enter the numbers : \n");
for (i=1;i<=num;i++)
scanf ("%d",&a[i]);
max = a[0];
min = a[0];
maxmin(1, num);
printf ("Minimum element in an array : %d\n", min);
printf ("Maximum element in an array : %d\n", max);
return 0;
}
OUTPUT:
RESULT:
Thus, the program to find out the maximum and minimum numbers in a given list of n
numbers using the divide and conquer technique has been implemented and executed
successfully.
29
EX.NO:2.a MERGE SORT
DATE:
AIM:
To implement Merge sort method to sort an array of elements and determine the time
required to sort. 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.
ALGORITHM:
step 1: start
step 2: declare array and left, right, mid variable
step 3: perform merge function.
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
step 4: Stop
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
30
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
31
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
OUTPUT:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
RESULT:
Thus, the C program for implementation of Merge sort algorithm was done and
executed successfully.
32
EX.NO: 2.b QUICK SORT
DATE:
AIM:
To implement Quick sort method to sort an array of elements and determine the time
required to sort. 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.
ALGORITHM:
PROGRAM:
#include <stdio.h>
int partition (int a[], int start, int end)
{ int pivot = a[end]; // pivot element
int i = (start - 1);
for (int j = start; j <= end - 1; j++)
{
if (a[j] < pivot)
{
33
i++;
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}
34
OUTPUT:
RESULT:
Thus, the C program for implementation of Quick sort algorithm was done and
executed successfully.
35
STATE SPACE SEARCH ALGORITHMS
AIM:
To Implement N Queens problem using Backtracking.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<math.h>
int a[30],count=0;
36
printf("*\t");
}
printf("\n");
}
}
void queen(int n){
int k=1;
a[k]=0;
while(k!=0){
a[k]=a[k]+1;
while((a[k]<=n)&&!place(k))
a[k]++;
if(a[k]<=n){
if(k==n)
print_sol(n);
else
{
k++;
a[k]=0;
}
}
else
k--;
}
}
void main(){
int i,n;
printf("Enter the number of Queens\n");
scanf("%d",&n);
queen(n);
printf("\nTotal solutions=%d",count);
}
37
OUTPUT:
RESULT:
Thus, the implementation of N Queens problem using Backtracking method was done
and executed successfully.
38
APPROXIMATION ALGORITHMS RANDOMIZED ALGORITHMS
AIM:
Implement any scheme to find the optimal solution for the Traveling Salesperson
problem and then solve the same problem instance using any approximation algorithm and
determine the error in the approximation.
ALGORITHM:
Step 1: Start
Step 2: Check for the disconnection between the current city and the next city
Step 2: Check whether the travelling sales person has visited all the cities
Step 3: Find the next city to be visited
Step 4: Find the solution and terminate
Step 5: End
PROGRAM:
#include<stdio.h>
int s,c[100][100],ver;
float optimum=999,sum;
/* function to swap array elements*/
void swap(int v[], int i, int j)
{
int t;
t = v[i]; v[i] = v[j];v[j] = t;
}
/* recursive function to generate permutations*/
39
if (i == n) {
if(v[0]==s)
{
for (j=0; j<n; j++)
printf ("%d ", v[j]);
sum1=0;
for( k=0;k<n-1;k++)
{
sum1=sum1+c[v[k]][v[k+1]];
}
sum1=sum1+c[v[n-1]][s];
printf("sum = %d\n",sum1);
if (sum1<optimum)
optimum=sum1;
}
}
else
// recursively explore the permutations starting at index i going through index n-
1*/for (j=i; j<n; j++)
{
swap (v, i, j); brute_force (v, n, i+1);
/* swap them back the way they were */
swap (v, i, j);
}
}
void nearest_neighbour(intver)
{
int min,p,i,j,vis[20],from;
for(i=1;i<=ver;i++)
vis[i]=0;
vis[s]=1; from=s;
sum=0;
for(j=1;j<ver;j++)
{
min=999;
for(i=1;i<=ver;i++)
if(vis[i] !=1 &&c[from][i]<min && c[from][i] !=0 )
40
{
min= c[from][i];
p=i;
}
vis[p]=1; from=p;
sum=sum+min;
}
sum=sum+c[from][s];
void main ()
{
int ver,v[100],i,j;
printf("Enter n : ");
scanf("%d",&ver);
for (i=0; i<ver; i++)
v[i] = i+1;
printf("Enter cost matrix\n");
for(i=1;i<=ver;i++)
for(j=1;j<=ver;j++)
scanf("%d",&c[i][j]);
printf("\nEnter source : ");
scanf("%d",&s);
brute_force (v, ver, 0);
printf("\nOptimum solution with brute force technique is=%f\n",optimum);
nearest_neighbour(ver);
printf("\nSolution with nearest neighbour technique
is=%f\n",sum);printf("The approximation val
is=%f",((sum/optimum)-1)*100);
printf(" % ");
}
41
OUTPUT:
RESULT:
Thus, the implementation of Travelling Salesman problem was done and executed
successfully.
42
EX.NO:2 RANDOMIZED ALGORITHMS FOR FINDING Kth SMALLEST NUMBER
DATE:
AIM:
To implement randomized algorithms for finding the kth smallest number.
ALGORITHM:
Step 1: Start
Step 3: Then partition to the array around the pivot, its help to all the smaller elements were placed
before the pivot and all greater elements are placed after the pivot.
Step 4: Then Check the position of the pivot. If it is the kth element then return it. If it is
greater than the kth element then repeat the process of the left sub array
Step 5: If it is less than the kth element then repeat the process of the sub array
Step 6: End
PROGRAM:
// If position is same as k
if (pos-l == k-1)
return arr[pos];
if (pos-l > k-1) // If position is more, recur for left subarray
return kthSmallest(arr, l, pos-1, k);
43
// Else recur for right subarray
return kthSmallest(arr, pos+1, r, k-pos+l-1);
}
44
OUTPUT:
RESULT:
Thus, the implementation of randomized algorithms for finding the kth
smallest number was done and executed successfully.
45