Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
57 views

CS3401- Algorithms

The document outlines the implementation of various searching and sorting algorithms in C, including Linear Search, Recursive Binary Search, Pattern Search, Insertion Sort, and Heap Sort. It details the algorithms, provides sample code, and discusses the execution results, including time taken for operations. Additionally, it introduces a Breadth First Search algorithm for graph traversal.

Uploaded by

c.muthupriya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

CS3401- Algorithms

The document outlines the implementation of various searching and sorting algorithms in C, including Linear Search, Recursive Binary Search, Pattern Search, Insertion Sort, and Heap Sort. It details the algorithms, provides sample code, and discusses the execution results, including time taken for operations. Additionally, it introduces a Breadth First Search algorithm for graph traversal.

Uploaded by

c.muthupriya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

SEARCHING AND SORTING ALGORITHMS:

1. Implement Linear Search. 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.

AIM:
To write a C program to implement Linear Search. 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:

Linear Search(Array A,Value x)


Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1

Step 5: Go to Step 2
Step 6: Printf Element x Found at index i and go to step 8
Step 7: Printf element not found
Step 8: Exit

PROGRAM:
#include <stdio.h>
#include <time.h>
int linearSearch(int arr[], int n, int x)
{
for (int i = 0; i < n; i++)
{
if (arr[i] == x)
{
return i;
}
}
return -1;
}

int main()
{ int n, x, pos;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the element to search: "); scanf("%d", &x);
clock_t start = clock();
pos = linearSearch(arr, n, x); clock_t end = clock();

if (pos == -1) {
printf("Element not found.\n");
}
else
{
printf("Element found at position %d.\n", pos);
}

double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;


printf("Time taken: %lf seconds.\n", time_taken);

return 0;
}

OUTPUT:

c1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Enter the number of elements: 12
Enter 12 elements:
2
3
6
9
10
13
16
26
26
15
56
45
Enter the element to search: 56
Element found at position 10.
Time taken: 0.000005 seconds.

Time N
0.000005 5
0.000002 7
0.000003 8
0.000005 10
0.000005 12
Graph:

RESULT:

Thus the C program for linear search algorithm was executed successfully and the output
was verified.
2. 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.

AIM :
To write a C program 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:
Step 1: Compare x with the middle element.
Step 2: If x matches with the middle element, we return the mid index.
Step 3: Else If x is greater than the mid element, then x can only lie in the right half subarray
after the mid element. So, we recur for the right half.
Step 4: Else (x is smaller) recur for the left half.
PROGRAM:
#include<stdio.h>
#include <time.h>
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
if (arr[mid] == x)
{
return mid;
}
if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int main()
{
int n, x, pos;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements in sorted order:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the element to search: ");
scanf("%d", &x);
clock_t start = clock();
pos = binarySearch(arr, 0, n - 1, x);
clock_t end = clock();
if (pos == -1) {
printf("Element not found.\n");
} else {
printf("Element found at position %d.\n", pos);
}
double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken: %lf seconds.\n", time_taken);
return 0;
}
OUTPUT:
c1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Enter the number of elements: 6
Enter 6 elements in sorted order:
8
10
12
14
15
16
Enter the element to search: 15
Element found at position 4.
Time taken: 0.000001 seconds.

RESULT:
Thus the C program for binary search algorithm was executed successfully and the output
was verified.
3. Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function search (char
pat [ ], char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume
that n > m.

AIM :
To write a C program to given a text txt [0...n-1] and a pattern pat [0...m-1], write a function
search (char pat [ ], char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may
assume that n > m.

ALGORITHM:

Step 1: We start the comparison of pat[j] with j = 0 with characters of the current window
of text.
Step 2: We keep matching characters txt[i] and pat[j] and keep incrementing i and j while
pat[j] and txt[i] keep matching.
Step 3: When we see a mismatch
1) We know that characters pat[0..j-1] match with txt[i-j…i-1] (Note that j starts with 0 and
increments it only when there is a match).
2) We also know (from the above definition) that lps[j-1] is the count of
characters of pat[0…j-1] that are both proper prefix and suffix.
3) From the above two points, we can conclude that we do not need to match these lps[j-1]
characters with txt[i-j…i-1] because we know that these characters will anyway match. Let
us consider the above example to understand this.

PROGRAM:
#include <stdio.h>
#include <string.h>
void search(char pat[], char txt[])
{
int m = strlen(pat);
int n = strlen(txt);

for (int i = 0; i <= n - m; i++)


{
int j;
for (j = 0; j < m; j++)
{
if (txt[i + j] != pat[j])
{ break;
}
}
if (j == m)
{
printf("Pattern found at position %d.\n", i);
}
}
}

int main()
{
char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA"; search(pat, txt);
return 0;
}

OUTPUT:

cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Pattern found at position 0.
Pattern found at position 9.
Pattern found at position 13.

RESULT:
Thus, the C program for Pattern search algorithm was executed successfully and the
output was verified.
4. Sort a given set of elements using the Insertion sort and 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.

AIM:
To write a c program to sort a given set of elements using the Insertion sort and 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 (INSERTION SORT):

Step 1: Start the program


Step 2: Iterate from arr[1] to arr[N] over the array.
Step 3: Compare the current element (key) to its predecessor.
Step 4: If the key element is smaller than its predecessor, compare it to the elements before.
Move the greater elements one position up to make space for the swapped element.
Step 5: Stop the program.
PROGRAM:
#include <math.h>
#include <stdio.h>
#include <time.h>
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;

/* Move elements of arr[0..i-1], that are greater


than key, to one position ahead of their current
position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

void printArray(int arr[], int n)


{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements in sorted order:\n", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
clock_t start = clock();
insertionSort(arr, n);
clock_t end = clock();
printArray(arr, n);
double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken: %lf seconds.\n", time_taken);
return 0;
}
OUTPUT:
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc ex1.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Enter the number of elements: 5
Enter 5 elements:
12
11
13
5
6
5 6 11 12 13
Time taken: 0.000001 seconds.
Time N
0.000001 5
0.000001 7
0.000003 8
0.000004 10
0.000005 12
ALGORITHM (HEAP SORT):

Step 1: Start the program


Step 2: Build a max heap from the input data.
Step 3: At this point, the maximum element is stored at the root of the heap. Replace
it with the last item of the heap followed by reducing the size of the heap by 1. Finally,
heapify the root of the tree.
Step 5: Repeat step 2 while the size of the heap is greater than 1.
Step 5: Stop the program
PROGRAM (HEAP SORT):
#include <stdio.h>
#include <time.h>

void swap(int* a, int* b)


{

int temp = *a;

*a = *b;

*b = temp;
}

void heapify(int arr[], int N, int i)


{
int largest = i;
int left = 2 * i + 1; int right = 2 * i + 2;
if (left < N && arr[left] > arr[largest]) largest = left;
if (right < N && arr[right] > arr[largest]) largest = right;
if (largest != i)
{
swap(&arr[i], &arr[largest]); heapify(arr, N, largest);
}
}

void heapSort(int arr[], int N)


{
for (int i = N / 2 - 1; i >= 0; i--) heapify(arr, N, i);
for (int i = N - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}

void printArray(int arr[], int N)


{
for (int i = 0; i < N; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main()

{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements in sorted order:\n", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
clock_t start = clock();
heapSort(arr, N);
clock_t end = clock();
printf("Sorted array is\n");
printArray(arr, N);
double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken: %lf seconds.\n", time_taken);
return 0;
}
OUTPUT:
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gedit heap.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc heap.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Enter the number of elements: 5
Enter 5 elements:
12
11
13
5
6
Sorted array is
5 6 7 11 12 13
Time taken: 0.000008 seconds.

Time N
0.000008 5
0.000008 7
0.000003 8
0.000002 10
0.000005 12
RESULT:
Thus, the c program for Insertion sort and Heap sort was executed successfully and the
output was verified.
GRAPH ALGORITHMS
5. Develop a program to implement graph traversal using Breadth First
Search

AIM :
To write a c program to develop a program to implement graph traversal using Breadth
First Search.

ALGORITHM:

Step 1: Consider the graph you want to navigate.


Step 2: Select any vertex in your graph, say v1, from which you want to traverse the
graph.
Step 3: Examine any two data structure for traversing the graph
Visited array (size of the graph)
Queue data structure
Step 4: Starting from the vertex, you will add to the visited array, and afterward, you will
v1’s adjacent vertices to the queue data structure.
Step 5: Now, using the FIFO concept, you must remove the element from the queue,
put it into the visited array, and then return to the queue to add the adjacent vertices of
the removed element.
Step 6: Repeat step 5 until the queue is not empty and no vertex is left to be visited.

PROGRAM:

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50

typedef struct Graph_t


{ int V;
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;

Graph* Graph_create(int V)
{
Graph* g = malloc(sizeof(Graph)); g->V = V;

for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++)


{
g->adj[i][j] = false;
}
}
return g;
}

void Graph_destroy(Graph* g)
{
free(g);
}

void Graph_addEdge(Graph* g, int v, int w)


{
g->adj[v][w] = true;
}

void Graph_BFS(Graph* g, int s)


{
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++)
{
visited[i] = false;
}

int queue[MAX_VERTICES];

int front = 0, rear = 0;


visited[s] = true;
queue[rear++] = s;
while (front != rear)
{
s = queue[front++];
printf("%d ", s);
for (int adjacent = 0; adjacent < g->V; adjacent++)
{
if (g->adj[s][adjacent] && !visited[adjacent])
{
visited[adjacent] = true;
queue[rear++] = adjacent;
}
}
}
}

int main()
{
Graph* g = Graph_create(4); Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3);
Graph_addEdge(g, 3, 3);
printf("Following is Breadth First Traversal " "(starting from vertex 2) \n");
Graph_BFS(g, 2);
Graph_destroy(g);
return 0;
}

OUTPUT:
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc bfs.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Following is Breadth First Traversal (starting from vertex 2)
2031

RESULT:

Thus the C program for breadth first search algorithm was executed successfully and
the output was verified.
6. Develop a program to implement graph traversal using Depth First Search

AIM :
To write a C program to develop a program to implement graph traversal using Depth
First Search.

ALGORITHM:

Step 1: Start by putting any one of the graph’s vertices at the back of the queue.
Step 2: Now take the front item of the queue and add it to the visited list.
Step 3: Create a list of that vertex's adjacent nodes. Add those which are not within
the visited list to the rear of the queue.
Step 4: Keep continuing steps two and three till the queue is empty.
Step 5: Stop the program

PROGRAM:
#include <stdio.h>

#include <stdlib.h>
int sourceV,Vertex,Edge,time,visited[10],Graph[10][10];
void DepthFirstSearch(int i)
{
int j; visited[i]=1;
printf(" %d->",i++);
for(j=0;j<Vertex;j++)
{
if(Graph[i][j]==1&&visited[j]==0)
DepthFirstSearch(j);
}
}
int main()
{
int i,j,vertex1,vertex2;
printf("\t\t\tGraphs\n");
printf("Enter no. of edges:");
scanf("%d",&Edge);
printf("Enter no. of vertices:");
scanf("%d",&Vertex); for(i=0;i<Vertex;i++)
{
for(j=0;j<Vertex;j++)
Graph[i][j]=0;
}
for(i=0;i<Edge;i++)
{
printf("Enter the edges in V1 V2 : ");
scanf("%d%d",&vertex1,&vertex2);
Graph[vertex1-1][vertex2-1]=1;
}
for(i=0;i<Vertex;i++)
{
for(j=0;j<Vertex;j++)
printf(" %d ",Graph[i][j]);
printf("\n");
}
printf("Enter source Vertex: ");
scanf("%d",&sourceV);
DepthFirstSearch(sourceV-1);
return 0;
}

OUTPUT:
c1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc dfs.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Graphs
Enter no. of edges:6
Enter no. of vertices:5
Enter the edges in V1 V2 : 1 2
Enter the edges in V1 V2 : 1 3
Enter the edges in V1 V2 : 2 5
Enter the edges in V1 V2 : 3 4
Enter the edges in V1 V2 : 2 4
Enter the edges in V1 V2 : 4 5
0 1 1 0 0
0 0 0 1 1
0 0 0 1 0
0 0 0 0 1
0 0 0 0 0
Enter source Vertex: 1
0-> 3-> 4->

RESULT:
Thus the C program for depth first search algorithm was executed successfully and the
output was verified.
7. From a given vertex in a weighted connected graph, develop a program to find the
shortest paths to other vertices using Dijkstra’s algorithm.

AIM :
To write a c program from a given vertex in a weighted connected graph, develop a
program to find the shortest paths to other vertices using Dijkstra’s algorithm.

ALGORITHM:

Step 1: Mark the source node with a current distance of 0 and the rest with infinity.
Step 2: Set the non-visited node with the smallest current distance as the current node.
Step 3: For each neighbor, N of the current node adds the current distance of the
adjacent node with the weight of the edge connecting 0->1. If it is smaller than the
current distance of Node, set it as the new current distance of N.
Step 4: Mark the current node 1 as visited.
Step 5: Go to step 2 if there are any nodes are unvisited .

PROGRAM:

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

#define V 9

int minDistance(int dist[], bool sptSet[])


{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}

void printSolution(int dist[])


{
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}

void dijkstra(int graph[V][V], int src)


{
int dist[V]; bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++)
{
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

printSolution(dist);
}

int main()
{
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

dijkstra(graph, 0);

return 0;
}

OUTPUT:
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc dj.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14

RESULT:

Thus the C program for depth first search algorithm was executed successfully and the
output was verified.
8. Find the minimum cost spanning tree of a given undirected graph using Prim’s
algorithm.

AIM:
To write a C program to find the minimum cost spanning tree of a given undirected
graph using Prim’s algorithm.

ALGORITHM:

Step 1: Determine an arbitrary vertex as the starting vertex of the MST.


Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST (known
as fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe
vertices. Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form any
cycle. Step 6: Return the MST and exit

PROGRAM:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 5

int minKey(int key[], bool mstSet[])


{
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

int printMST(int parent[], int graph[V][V])


{
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++)
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}

void primMST(int graph[V][V])


{
int parent[V]; int key[V];
bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0;

parent[0] = -1;
for (int count = 0; count < V - 1; count++)
{
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

printMST(parent, graph);
}

int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

primMST(graph);

return 0;
}

OUTPUT:

c1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc prims.c


cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5

RESULT:

Thus, the C program for depth first search algorithm was executed successfully and the
output was verified.
9. Implement Floyd’s algorithm for the All-Pairs- Shortest- Paths problem.

AIM :
To write a C program to Implement Floyd’s algorithm for the All-Pairs- Shortest-
Paths problem.

ALGORITHM:

Step 1: Initialize the solution matrix same as the input graph matrix as a first step.
Step 2: Then update the solution matrix by considering all vertices as an
intermediate vertex.
Step 3: The idea is to one by one pick all vertices and updates all shortest paths
which include the picked vertex as an intermediate vertex in the shortest path.
Step 4: When we pick vertex number k as an intermediate vertex, we already
have considered vertices {0, 1, 2, .. k-1} as intermediate vertices.
Step 5: For every pair (i, j) of the 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] as dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] +
dist[k][j]
PROGRAM:

#include <stdio.h>
#define V 4
#define INF 99999

void printSolution(int dist[][V]);


void floydWarshall(int dist[][V])
{
int i, j, k;
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
printSolution(dist);
}
void printSolution(int dist[][V])
{
printf("The following matrix shows the shortest distances between every pair of vertices \n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}

int main()
{
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };

floydWarshall(graph);
return 0;
}
OUTPUT:

cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc floyd.c


cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
The following matrix shows the shortest distances between every pair of vertices
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 0

RESULT:

Thus, the C program for Floyd’s algorithm was executed successfully and the output
was verified.
10. Compute the transitive closure of a given directed graph using Warshall's
algorithm

AIM:
To write a C program to compute the transitive closure of a given directed graph using
Warshall's algorithm.

ALGORITHM:

Step 1: Start the program


Step 2: Instead of an integer resultant matrix (dist[V][V] in floyd warshall), we can
create a Boolean reach-ability matrix reach[V][V] (we save space). The value
reach[i][j] will be 1 if j is reachable from i, otherwise 0.
Step 3: Instead of using arithmetic operations, we can use logical operations. For
arithmetic operation ‘+’, logical and ‘&&’ is used, and for a ‘-‘, logical or ‘||’ is used.
(We save time by a constant factor. Time complexity is the same though)
Step 4: Stop the program

PROGRAM:
#include<stdio.h>
#include<math.h>
int max(int, int);
void warshal(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++)
p[i][j] = max(p[i][j], p[i][k] && p[k][j]);
}
int max(int a, int b)
{
if (a > b)
return (a);
else
return (b);
}
void main()
{
int p[10][10] = { 0 }, n, e, u, v, i, j;
printf("\n Enter the number of vertices:");
scanf("%d", &n);
printf("\n Enter the number of edges:");
scanf("%d", &e);
for (i = 1; i <= e; i++)
{
printf("\n Enter the end vertices of edge %d:", i);
scanf("%d%d", &u, &v);
p[u][v] = 1;
}
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");
}
warshal(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");
}
}
OUTPUT:
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc war.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out

Enter the number of vertices:5

Enter the number of edges:6

Enter the end vertices of edge 1:1 2

Enter the end vertices of edge 2:1 3

Enter the end vertices of edge 3:2 5

Enter the end vertices of edge 4:3 4

Enter the end vertices of edge 5:2 4

Enter the end vertices of edge 6:4 5

Matrix of input data:


0 1 1 0 0
0 0 0 1 1
0 0 0 1 0
0 0 0 0 1
0 0 0 0 0

Transitive closure:
0 1 1 1 1
0 0 0 1 1
0 0 0 1 1
0 0 0 0 1
0 0 0 0 0

RESULT:
Thus the C program for Warshall's algorithm was executed successfully and the output
was verified.
ALGORITHM DESIGN TECHNIQUES:

11. Develop a program to find out the maximum and minimum numbers in a
given list of n numbers using the divide and conquer technique.

AIM :
To write a C program 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:

Step 1: Start the program.


Step 2: Divide array by calculating mid index i.e. mid = l + (r — l)/2
Step 3: Recursively find the maximum and minimum of left part by calling the same
function i.e. leftMinMax[2] = minMax(X, l, mid)
Step 4: Recursively find the maximum and minimum for right part by calling the
same function i.e. rightMinMax[2] = minMax(X, mid + 1, r)
Step 5: Finally, get the overall maximum and minimum by comparing the min and max
of both halves.
Step 6: Stop.

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];
}
}
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:
c1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc divide.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out

Enter the total number of numbers : 8


Enter the numbers :
5
8
2
90
100
23
45
56
Minimum element in an array : 2
Maximum element in an array : 100

RESULT:

Thus, the C program for finding maximum and minimum numbers in a given list of n
numbers using the divide and conquer technique was executed successfully and the
output was verified.
12. Implement Merge sort and Quick sort methods 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

AIM:
To write a C program to implement Merge sort and Quick sort methods 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 (MERGE SORT):

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>
#include <time.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}

int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
clock_t start = clock();
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
clock_t end = clock();
double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken: %lf seconds.\n", time_taken);
return 0;
}
OUTPUT:
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc merge.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Enter the number of elements: 6
Enter 6 elements:
12
11
13
5
6
7
Sorted array is
5 6 7 11 12 13
Time taken: 0.000006 seconds.
Time N
0.000006 6
0.000008 7
0.000003 8
0.000002 10
0.000005 12
ALGORITHM (QUICK SORT):

Step 1: Create a recursive function (say quicksort()) to implement the quicksort.


Step 2: Partition the range to be sorted (initially the range is from 0 to N-1) and return
the correct position of the pivot (say pi).

• Select the rightmost value of the range to be the pivot.


• Iterate from the left and compare the element with the pivot and perform the
partition as shown above.
• Return the correct position of the pivot.

Step 3: Recursively call the quicksort for the left and the right part of the pi.

PROGRAM (QUICK SORT):

#include <stdio.h>
#include <time.h>
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}

int partition(int arr[], int low, int high)


{
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
if (arr[j] < pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

void quickSort(int arr[], int low, int high)


{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
clock_t start = clock();
quickSort(arr, 0, N - 1);
printf("Sorted array: \n");
for (int i = 0; i < N; i++)
printf("%d ", arr[i]);
clock_t end = clock();
double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("\nTime taken: %lf seconds.\n", time_taken);
return 0;
}
OUTPUT:
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc quick.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Enter the number of elements: 6
Enter 6 elements:
8
9
10
5
1
7
Sorted array:
1 5 7 8 9 10
Time taken: 0.000005 seconds.
Time N
0.000005 6
0.000008 7
0.000003 8
0.000004 10
0.000005 12

RESULT:

Thus, the C program Merge sort and Quick sort methods for was executed
successfully and the output was verified.
STATE SPACE SEARCH ALGORITHMS:
13. Implement N Queens problem using Backtracking

AIM:
To write a C program to implement N Queens problem using Backtracking.

ALGORITHM:

Step 1: Initialize an empty chessboard of size NxN.


Step 2: Start with the leftmost column and place a queen in the first row of that column.
Step 3: Move to the next column and place a queen in the first row of that column.
Step 4: Repeat step 3 until either all N queens have been placed or it is impossible
to place a queen in the current column without violating the rules of the problem.
Step 5: If all N queens have been placed, print the solution.
Step 6: If it is not possible to place a queen in the current column without violating
the rules of the problem, backtrack to the previous column.
Step 7: Remove the queen from the previous column and move it down one row.
Step 8: Repeat steps 4-7 until all possible configurations have been tried.

PROGRAM:
#define N 8
#include <stdbool.h>
#include <stdio.h>

void printSolution(int board[N][N])


{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf(" %d ", board[i][j]);
printf("\n");
}
}

bool isSafe(int board[N][N], int row, int col)


{
int i, j;
for (i = 0; i < col; i++)
if (board[row][i])
return false;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;
return true;
}

bool solveNQUtil(int board[N][N], int col)


{
if (col >= N)
return true;
for (int i = 0; i < N; i++)
{
if (isSafe(board, i, col))
{
board[i][col] = 1;
if (solveNQUtil(board, col + 1))
return true;
board[i][col] = 0; // BACKTRACK
}
}
return false;
}

bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };

if (solveNQUtil(board, 0) == false)
{
printf("Solution does not exist"); return false;
}
printSolution(board); return true;
}
int main()
{
solveNQ();
return 0;
}
OUTPUT:
c1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc nqueen.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0

RESULT:
Thus, the C program n queens problem was executed successfully and the output
was verified.
APPROXIMATION ALGORITHMS RANDOMIZED ALGORITHMS
14. 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

AIM:
To write a C program to 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 on an arbitrary vertex as current vertex.


Step 2: Find out the shortest edge connecting current vertex and an unvisited vertex
V. Step 3: Set current vertex to V.
Step 4: Mark V as visited.
Step 5: If all the vertices in domain are visited, then terminate.
Step 6: Go to step 2.
Step 7: The sequence of the visited vertices is the output of the algorithm.
PROGRAM:
#include<stdio.h>
int a[10][10],n,visit[10];
int cost_opt=0,cost_apr=0;
int least_apr(int c);
int least_opt(int c);

void mincost_opt(int city)


{
int i,ncity; visit[city]=1;
printf("%d-->",city);
ncity=least_opt(city);
if(ncity==999)
{
ncity=1;
printf("%d",ncity);
cost_opt+=a[city][ncity];
return;
}
mincost_opt(ncity);
}
void mincost_apr(int city)
{
int i,ncity; visit[city]=1;
printf("%d-->",city);
ncity=least_apr(city);
if(ncity==999)
{
ncity=1; printf("%d",ncity);
cost_apr+=a[city][ncity];
return;
}
mincost_apr(ncity);
}

int least_opt(int c)
{
int i,nc=999;
int min=999,kmin=999;
for(i=1;i<=n;i++)
{
if((a[c][i]!=0)&&(visit[i]==0))

if(a[c][i]<min)
{
min=a[i][1]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost_opt+=kmin;
return nc;
}

int least_apr(int c)
{
int i,nc=999;
int min=999,kmin=999;
for(i=1;i<=n;i++)
{
if((a[c][i]!=0)&&(visit[i]==0))
if(a[c][i]<kmin)
{
min=a[i][1]+a[c][i]; kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost_apr+=kmin;
return nc;
}
void main()
{
int i,j;
printf("Enter No. of cities:\n");
scanf("%d",&n);

printf("Enter the cost matrix\n");


for(i=1;i<=n;i++)
{
printf("Enter elements of row:%d\n",i );
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
visit[i]=0;
}

printf("The cost list is \n");


for(i=1;i<=n;i++)
{
printf("\n\n");
for(j=1;j<=n;j++)
printf("\t%d",a[i][j]);
}
printf("\n\n Optimal Solution :\n");
printf("\n The path is :\n");
mincost_opt(1);
printf("\n Minimum cost:");
printf("%d",cost_opt);

printf("\n\n Approximated Solution :\n");


for(i=1;i<=n;i++)
visit[i]=0;
printf("\n The path is :\n");
mincost_apr(1);
printf("\nMinimum cost:");
printf("%d",cost_apr);
printf("\n\nError in approximation is approximated solution/optimal
solution=%f",(float)cost_apr/cost_opt);
}
OUTPUT:
cc124-HP-280-G4-MT-Business-PC:~$ gcc tsp.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Enter No. of cities:
4
Enter the cost matrix
Enter elements of row:1
0136
Enter elements of row:2
1023
Enter elements of row:3
3201
Enter elements of row:4
6310
The cost list is

0 1 3 6

1 0 2 3

3 2 0 1

6 3 1 0

Optimal Solution :

The path is :
1-->2-->4-->3-->1
Minimum cost:8

Approximated Solution :

The path is :
1-->2-->3-->4-->1
Minimum cost:10

Error in approximation is approximated solution/optimal solution=1.250000

RESULT:
Thus, the C program to find the optimal solution for the Traveling Salesperson problem
to find the optimal solution for the Traveling Salesperson problem was executed successfully
and the output was verified
15. Implement randomized algorithms for finding the kth smallest number

AIM:
To write a C program to implement randomized algorithms for finding the kth
smallest number.

ALGORITHM:

Step 1: find the k'th element in A using 'selection algorithm', let it be 'z'
Step 2: initialize an empty list 'L'
Step 3: initialize counter<-0
Step 4: for each element in
A:
4.1 : if element < z:
4.1.1 : counter<-counter + 1;
L.add(element)
Step 5: for each element in A:
5.1 : if element == z AND count < k:
5.1.1 : counter<-counter + 1;
L.add(element)
Step 6: return L

PROGRAM:

#include <limits.h>

#include <stdio.h>

int partition(int arr[], int l, int r);

int kthSmallestelem(int arr[], int l, int r, int K)


{
if (K > 0 && K <= r - l + 1)
{
int pos = partition(arr, l, r);
if (pos - l == K - 1)
return arr[pos];
if (pos - l > K - 1)

return kthSmallestelem(arr, l, pos - 1, K);

return kthSmallestelem(arr, pos + 1, r, K - pos + l - 1);


}

return INT_MAX;
}

void swap(int* a, int* b)


{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int l, int r)
{
int x = arr[r], i = l;
for (int j = l; j <= r - 1; j++)
{
if (arr[j] <= x) {
swap(&arr[i], &arr[j]);
i++;
}
}

swap(&arr[i], &arr[r]);
return i;
}

int main()
{

int arr[100]; int N, K;


printf("Enter the No.of Elements:");
scanf("%d",&N);
for(int i=0;i<N;i++)
{
printf("Enter the Number:");
scanf("%d",&arr[i]);
}
printf("Enter the k th position value:");
scanf("%d",&K);
printf("K'th smallest element is %d",kthSmallestelem(arr, 0, N - 1, K));
return 0;
}
OUTPUT:
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ gcc kth.c
cc1-24@cc124-HP-280-G4-MT-Business-PC:~$ ./a.out
Enter the No.of Elements:8
Enter the Number:23
Enter the Number:24
Enter the Number:25
Enter the Number:28
Enter the Number:29
Enter the Number:32
Enter the Number:33
Enter the Number:35
Enter the k th position value:4
K'th smallest element is 28

RESULT:
Thus, the C program to implement randomized algorithms for finding the kth
smallest number was executed successfully and the output was verified.

You might also like