0% found this document useful (0 votes)
5 views

DAA manual-C programming

The document outlines several C programming tasks, including implementing linear and binary search algorithms, pattern searching, sorting methods (insertion and heap sort), and graph traversal techniques (BFS and DFS). Each section includes the aim, algorithm, program code, and results indicating successful execution. The tasks involve measuring execution time and plotting graphs for performance analysis.

Uploaded by

sangeethasegar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

DAA manual-C programming

The document outlines several C programming tasks, including implementing linear and binary search algorithms, pattern searching, sorting methods (insertion and heap sort), and graph traversal techniques (BFS and DFS). Each section includes the aim, algorithm, program code, and results indicating successful execution. The tasks involve measuring execution time and plotting graphs for performance analysis.

Uploaded by

sangeethasegar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

1.lmplement 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 arrJJ, int n, int x)


{ for (int i = 0; i < n; i++) {
if (arrJiJ == x) {
return i;
}
}
return -1;
}

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);
}

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:

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>

int binarySearch(int arrJJ, int l, int r, int x) {


if (r >= l) {
int mid = l + (r - l) / 2;

if (arrJmidJ == x) {
return mid;
}

if (arrJmidJ > 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 arrJnJ;
printf(”Enter %d elements in sorted order:\n”, n);
for (int i = 0; i < n; i++) {
scanf(”%d”, &arrJiJ);
}

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:

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:

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 patJJ, char txtJJ)


{ 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 (txtJi + jJ != patJjJ)
{ break;
}
}
if (j == m) {
printf(”Pattern found at position %d.\n”, i);
}
}
}

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.

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( INSERTION SORT ):


#include <math.h>
#include <stdio.h>
#include <time.h>
void insertionSort(int arrJJ, int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arrJiJ;
j = i - 1;

/* Move elements of arrJ0..i-1J, that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arrJjJ > key) {
arrJj + 1J = arrJjJ;
j = j - 1;
}
arrJj + 1J = key;
}
}

void printArray(int arrJJ, int n)


{
int i;
for (i = 0; i < n; i++)
printf(”%d ”, arrJiJ);
printf(”\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:

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>
void swap(int* a, int* b)
{

int temp = *a;

*a = *b;

*b = temp;
}

void heapify(int arrJJ, int N, int i)


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

void heapSort(int arrJJ, int N)


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

void printArray(int arrJJ, int N)


{
for (int i = 0; i < N; i++)
printf(”%d ”, arrJiJ);
printf(”\n”);
}

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.

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 adjJMAX_VERTICESJJMAX_VERTICESJ;
} 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->adjJiJJjJ = false;
}
}

return g;
}

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

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


{
g->adjJvJJwJ = true;
}

void Graph_BFS(Graph* g, int s)


{
bool visitedJMAX_VERTICESJ;
for (int i = 0; i < g->V; i++) {
visitedJiJ = false;
}

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.

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,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

int minDistance(int distJJ, bool sptSetJJ)


{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSetJvJ == false && distJvJ <=
min) min = distJvJ, min_index = v;
return min_index;
}

void printSolution(int distJJ)


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

void dijkstra(int graphJVJJVJ, int src)


{
int distJVJ;
bool
sptSetJVJ;
for (int i = 0; i < V; i++)
distJiJ = INT_MAX, sptSetJiJ = false;
distJsrcJ = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSetJuJ = true;
for (int v = 0; v < V; v++)
if (!sptSetJvJ && graphJuJJvJ
&& distJuJ != INT_MAX
&& distJuJ + graphJuJJvJ < distJvJ)
distJvJ = distJuJ + graphJuJJvJ;
}

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

int minKey(int keyJJ, bool mstSetJJ)


{
int min = INT_MAX, min_index;

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


if (mstSetJvJ == false && keyJvJ < min)
min = keyJvJ, min_index = v;

return min_index;
}

int printMST(int parentJJ, int graphJVJJVJ)


{
printf(”Edge \tWeight\n”);
for (int i = 1; i < V; i++)
printf(”%d - %d \t%d \n”, parentJiJ,
i, graphJiJJparentJiJJ);
}

void primMST(int graphJVJJVJ)


{
int parentJVJ;
int keyJVJ;
bool mstSetJVJ;
for (int i = 0; i < V; i++)
keyJiJ = INT_MAX, mstSetJiJ = false;
keyJ0J = 0;

parentJ0J = -1;

for (int count = 0; count < V - 1; count++) {


int u = minKey(key, mstSet);
mstSetJuJ = true;
for (int v = 0; v < V; v++)
if (graphJuJJvJ && mstSetJvJ == false
&& graphJuJJvJ < keyJvJ)
parentJvJ = u, keyJvJ = graphJuJJvJ;
}

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

void printSolution(int distJJJVJ);


void floydWarshall(int distJJJVJ)
{
int i, j, k;
for (k = 0; k < V; k++) {
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
if (distJiJJkJ + distJkJJjJ < distJiJJjJ)
distJiJJjJ = distJiJJkJ + distJkJJjJ;
}
}
}
printSolution(dist);
}
void printSolution(int distJJJVJ)
{
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 (distJiJJjJ == INF)
printf(”%7s”, ”INF”);
else
printf(”%7d”, distJiJJjJ);
}
printf(”\n”);
}
}

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;

void maxmin(int i, int j)


{
int max1, min1, mid;
if(i==j)
{
max = min = aJiJ;
}
else
{
if(i == j-1)
{
if(aJiJ <aJjJ)
{
max = aJjJ;
min = aJiJ;
}
else
{
max = aJiJ;
min = aJjJ;
}
}
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”,&aJiJ);
max = aJ0J;
min = aJ0J;
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 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.

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 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);
}
}

void printArray(int AJJ, int size)


{
int i;
for (i = 0; i < size; i++)
printf(”%d ”, AJiJ);
printf(”\n”);
}

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:

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 arrJJ, int low, int high)


{
int pivot = arrJhighJ;
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arrJjJ < pivot) {
i++;
swap(&arrJiJ, &arrJjJ);
}
}
swap(&arrJi + 1J, &arrJhighJ);
return (i + 1);
}

void quickSort(int arrJJ, 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()
{
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.

ALGORITHM (MERGE SORT):


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 boardJNJJNJ)


{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf(” %d ”, boardJiJJjJ);
printf(”\n”);
}
}

bool isSafe(int boardJNJJNJ, int row, int col)


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

bool solveNQUtil(int boardJNJJNJ, int col)


{
if (col >= N)
return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
boardJiJJcolJ = 1;
if (solveNQUtil(board, col + 1))
return true;
boardJiJJcolJ = 0; // BACKTRACK
}
}
return false;
}
bool solveNQ()
{
int boardJNJJNJ = { { 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:

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);

void mincost_opt(int city)


{
int i,ncity;
visitJcityJ=1;
printf(”%d-->”,city);
ncity=least_opt(city);
if(ncity==999)
{
ncity=1;
printf(”%d”,ncity);
cost_opt+=aJcityJJncityJ;
return;
}
mincost_opt(ncity);
}
void mincost_apr(int city)
{
int i,ncity;
visitJcityJ=1;
printf(”%d-->”,city);
ncity=least_apr(city);
if(ncity==999)
{
ncity=1;
printf(”%d”,ncity);
cost_apr+=aJcityJJncityJ;
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((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);

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”,&aJiJJjJ);
visitJiJ=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”,aJiJJjJ);
}
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++)
visitJiJ=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:

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>

int partition(int arrJJ, int l, int r);

int kthSmallestelem(int arrJJ, 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 arrJposJ;
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 arrJJ, int l, int r)
{
int x = arrJrJ, i = l;
for (int j = l; j <= r - 1; j++) {
if (arrJjJ <= x) {
swap(&arrJiJ, &arrJjJ); i+
+;
}
}

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy