DAA manual-C programming
DAA manual-C programming
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
int main() {
int n, x,
pos;
printf(”Enter the number of elements: ”);
scanf(”%d”, &n);
int arrJnJ;
printf(”Enter %d elements:\n”, n);
for (int i = 0; i < n; i++) {
scanf(”%d”, &arrJiJ);
}
if (pos == -1) {
printf(”Element not found.\n”);
} else {
printf(”Element found at position %d.\n”, pos);
}
return 0;
}
OUTPUT:
RESULT:
Thus the C program for linear search algorithm was executed successfully and the
output was verified.
2.lmplement 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>
if (arrJmidJ == x) {
return mid;
}
if (arrJmidJ > x) {
return binarySearch(arr, l, mid - 1, x);
}
return -1;
}
int main() {
int n, x,
pos;
printf(”Enter the number of elements: ”);
scanf(”%d”, &n);
int arrJnJ;
printf(”Enter %d elements in sorted order:\n”, n);
for (int i = 0; i < n; i++) {
scanf(”%d”, &arrJiJ);
}
if (pos == -1) {
printf(”Element not found.\n”);
} else {
printf(”Element found at position %d.\n”, pos);
}
return 0;
}
OUTPUT:
RESULT:
Thus the C program for recursive 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:
PROGRAM:
#include <stdio.h>
#include <string.h>
int main() {
char txtJJ = ”AABAACAADAABAAABAA”;
char patJJ = ”AABA”;
search(pat, txt);
return 0;
}
OUTPUT:
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 lnsertion
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.
int main()
{
int arrJJ = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) /
sizeof(arrJ0J); 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:
*a = *b;
*b = temp;
}
int main()
{
int arrJJ = { 12, 11, 13, 5, 6, 7 };
int N = sizeof(arr) /
sizeof(arrJ0J); heapSort(arr,
N);
printf(”Sorted array is\n”);
printArray(arr, N);
}
OUTPUT:
RESULT:
Thus the c program for Pattern search algorithm was executed successfully and the
output was verified.
ALGORITHM:
PROGRAM:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES
50
Graph* Graph_create(int V)
{
Graph* g = malloc(sizeof(Graph));
g->V = V;
return g;
}
void Graph_destroy(Graph* g) {
free(g);
}
int queueJMAX_VERTICESJ;
int front = 0, rear = 0;
visitedJsJ = true;
queueJrear++J = s;
while (front != rear) {
s = queueJfront+
+J; printf(”%d ”, s);
for (int adjacent = 0; adjacent < g->V;
adjacent++) {
if (g->adjJsJJadjacentJ && !visitedJadjacentJ) {
visitedJadjacentJ = true;
queueJrear++J = 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:
RESULT:
Thus the C program for breadth first search algorithm was executed successfully and the
output was verified.
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,visitedJ10J,GraphJ10JJ10J;
void DepthFirstSearch(int i)
{
int j;
visitedJiJ=1;
printf(” %d->”,i++);
for(j=0;j<Vertex;j++)
{
if(GraphJiJJjJ==1&&visitedJjJ==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++)
GraphJiJJjJ=0;
}
for(i=0;i<Edge;i++)
{
printf(”Enter the edges in V1 V2 : ”);
scanf(”%d%d”,&vertex1,&vertex2);
GraphJvertex1-1JJvertex2-1J=1;
}
for(i=0;i<Vertex;i++)
{
for(j=0;j<Vertex;j++)
printf(” %d ”,GraphJiJJjJ);
printf(”\n”);
}
printf(”Enter source Vertex:
”); scanf(”%d”,&sourceV);
DepthFirstSearch(sourceV-1);
return 0;
}
OUTPUT:
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
printSolution(dist);
}
int main()
{
int graphJVJJVJ = { { 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:
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
return min_index;
}
parentJ0J = -1;
printMST(parent, graph);
}
int main()
{
int graphJVJJVJ = { { 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:
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
V4
#define INF 99999
int main()
{
int graphJVJJVJ = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };
floydWarshall(graph);
return 0;
}
OUTPUT:
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 pJ10JJ10J, int n)
{ int i, j, k;
for (k = 1; k <= n; k++)
for (i = 1; i <= n; i+
+)
for (j = 1; j <= n; j++)
pJiJJjJ = max(pJiJJjJ, pJiJJkJ && pJkJJjJ);
}
int max(int a, int b) {
;
if (a > b)
return (a);
else
return (b);
}
void main() {
int pJ10JJ10J = { 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);
pJuJJvJ = 1;
}
printf(”\n Matrix of input data: \
n”); for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf(”%d\t”, pJiJJjJ);
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”, pJiJJjJ);
printf(”\n”);
}
}
OUTPUT:
RESULT:
Thus the C program for Warshall's algorithm was executed successfully and the output
was verified.
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 aJ100J;
OUTPUT:
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. lmplement 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.
#include <stdio.h>
#include
<stdlib.h>
#include <time.h>
void merge(int arrJJ, int
l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int LJn1J, RJn2J;
for (i = 0; i < n1; i++)
LJiJ = arrJl + iJ;
for (j = 0; j < n2; j++)
RJjJ = arrJm + 1 + jJ;
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (LJiJ <= RJjJ)
{
arrJkJ = LJiJ; i+
+;
}
else
{
arrJkJ = RJjJ;
j++;
}
k++;
}
while (i < n1) {
arrJkJ = LJiJ;
i++;
k++;
}
while (j < n2)
{
arrJkJ = RJjJ;
j++;
k++;
}
}
void mergeSort(int arrJJ,
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);
}
}
int main()
{
clock_t start = clock();
int arrJJ = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr) /
sizeof(arrJ0J); printf(”Given array is \
n”); 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:
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 main()
{
clock_t start = clock();
int arrJJ = { 10, 7, 8, 9, 1, 5 };
int N = sizeof(arr) /
sizeof(arrJ0J); quickSort(arr, 0,
N - 1); printf(”Sorted array: \n”);
for (int i = 0; i < N; i+
+) printf(”%d ”, arrJiJ);
clock_t end = clock();
double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC; printf(”\
nTime taken: %lf seconds.\n”, time_taken);
return 0;
}
OUTPUT:
RESULT:
Thus the C program Merge sort and Quick sort methods for was executed successfully
and the output was verified.
13. lmplement N Queens problem using Backtracking
AIM :
To write a C program to implement N Queens problem using Backtracking.
PROGRAM:
#define N 8
#include <stdbool.h>
#include <stdio.h>
if (solveNQUtil(board, 0) == false)
{ printf(”Solution does not
exist”); return false;
}
printSolution(board);
return true;
}
int main()
{
solveNQ();
return 0;
}
OUTPUT:
RESULT:
Thus the C program Merge sort and Quick sort methods was executed successfully and
the output was verified.
14. lmplement 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 aJ10JJ10J,n,visitJ10J;
int cost_opt=0,cost_apr=0;
int least_apr(int c);
int least_opt(int c);
int least_opt(int c)
{
int i,nc=999;
int min=999,kmin=999;
for(i=1;i<=n;i++)
{
if((aJcJJiJ!=0)&&(visitJiJ==0))
if(aJcJJiJ<min)
{
min=aJiJJ1J+aJcJJiJ;
kmin=aJcJJiJ;
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((aJcJJiJ!=0)&&(visitJiJ==0))
if(aJcJJiJ<kmin)
{
min=aJiJJ1J+aJcJJiJ;
kmin=aJcJJiJ;
nc=i;
}
}
if(min!=999)
cost_apr+=kmin;
return nc;
}
void main()
{
int i,j;
printf(”Enter No. of cities:\n”);
scanf(”%d”,&n);
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. lmplement 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>
if (pos - l == K - 1)
return arrJposJ;
if (pos - l > K - 1)
return INT_MAX;
}
swap(&arrJiJ, &arrJrJ);
return i;
}
int main()
{
int arrJ100J;
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”,&arrJiJ);
}
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:
RESULT:
Thus the C program to implement randomized algorithms for finding the kth smallest
number was executed successfully and the output was verified.