Algorithm CS3401 5 2 59

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

TABLE OF CONTENTS

S.No. Date List Of Experiments Page Mark Faculty


No. Signature
A. Searching and Sorting Algorithms

1 Linear Search
2 Binary Search
3 String Matching
4 (i)Insertion Sort
(ii)Heap sort
B. Graph Algorithms
1 Breadth First Search
2 Depth First Search
3 Dijkstra’s algorithm.
4 Prim’s algorithm
5 Floyd’s algorithm
6 Warshall's algorithm
C. Algorithm Design Techniques
1 Divide and conquer technique
(i)Merge sort
2
(ii)Quick sort
D. State Space Search Algorithms
1 N Queens problem using Backtracking.
E. Approximation Algorithms
Randomized Algorithms
1 Traveling Salesperson problem
2 Kth smallest number
Ex.no:A.1
LINEAR SEARCH
Date:

AIM:

To write a C program to implement the Linear search using time.h on c programming.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Get the header files and get the inputs, start=clock();

STEP 3: Enter the length of the array and get the search element from user.

STEP 4: compare the search element with the first element in the first.

STEP 5: If both are matching then display “Given element found!!!” and terminate then fn.

STEP 6: else compare search element with next element in the list.

STEP 7: Repeat step 4 and 5 & 6until the search element in the list.

STEP 8: If the last element in the list also doesn’t match, then display “Element not found”
and terminate the function.

STEP 9: At last calculate the time, when the program was executed.

STEP10: Finally calculate end the time and calculate both end and starting time.

STEP11: Stop the program.

PROGRAM:

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

{ int array[100], search,


c, n; clock_t start,end;
double total,i;
start=clock();

5
printf(“\n Start of the clock %ld”,start);
printf("\nEnter number of elements in
array\n"); scanf("%d", &n); printf("Enter
%d integer(s)\n", n); for (c = 0; c < n; c++)
scanf("%d", &array[c]); printf("Enter a
number to search\n"); scanf("%d", &search);
for (c = 0; c < n; c++)

{ if (array[c] == search) /* If required element is


found */

{
printf("%d is present at location %d.\n", search, c+1);
break;

} } if (c == n) printf("%d isn't present


in the array.\n", search); end=clock();
printf("\n End: %ld",end); total=(double)(end-
start)/CLOCKS_PER_SEC; printf("\n Total of
the clock %f",total); return 0;

OUTPUT:
Performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the C program implemented Linear search executed and output was verified
successfully.

7
Ex.no:A.2
BINARY SEARCH
Date:

AIM:

To write a C program to implement the Binary search using time.h on c programming.

ALGORITHM:

STEP 1: Start the program.

STEP 2: get the header file and the inputs and read the search element from the user.

STEP 3: Find the middle element in the list

STEP 4: compare,the search element with the middle element in sorted list.

STEP 5: If both are matching,then display “Given element found!!!” and terminate the
function.

STEP 6:I fboth are not match,then check the search element is smaller or larger than middle
element.

STEP 7: If smaller than middle element ,then repeated 3,4,5and6 steps for left sublist of
middle element.

STEP 8: If larger then middle element,then repeated 3,4.5&6 steps for right sublist of middle
element .

STEP 9:Repeat the same process until we find the search element in the list or until sublist
contains only one element.

STEP 10:Finally calculate the end time and add starting and ending time.

STEP 11: Stop the program.

PROGRAM
#include <stdio.h>

int recursiveBinarySearch(int array[]),

int start_index,

int end_index,

int element){

if (end_index >= start_index){

int middle = start_index + (end_index - start_index )/2;

if (array[middle] == element)

return middle;

if (array[middle] > element)

return recursiveBinarySearch(array, start_index, middle-1, element);

return recursiveBinarySearch(array, middle+1, end_index, element);

} return -1;}

int main(void){

int array[] = {1, 4, 7, 9, 16, 56, 70}; int n = 7; int element

= 9; int found_index = recursiveBinarySearch(array, 0, n-1,

element); if(found_index == -1 ) { printf("Element not

found in the array ");

else

printf("Element found at index : %d",found_index); }

return 0;}

9
OUTPUT:

Performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the C program implemented Binary search executed and output was verified
successfully.
Ex.no:A.3
STRING MATCHING
Date:

AIM:

To write a C program to implement a string matching program by using time.h .

ALGORITHM:

STEP 1: Start the program.

STEP 2: Get the headerfiles , clock & the inputs.

STEP 3:Include the starting time after the headerfiles and also inputs for calculating time.

STEP 4: Performs a checking at all position in the between to n-m whether an occurance of
pattern start there are not.

STEP 5: After each attempt if shifts the pattern by exactly one position to the right.

STEP 6: If the match is found then it shifts the pattern by exactly one position to the right.

STEP 7: End the program by ending time.

STEP 8: Stop the program.

PROGRAM:

#include <stdio.h>
#include <string.h> int
match(char [], char []);
int main() {

char a[100],
b[100]; int
position;

printf("Enter some text\n");


gets(a); printf("Enter a string
to find\n"); gets(b); position
= match(a, b);

11
if (position != -1)
{ printf("Found at location: %d\n", position
+ 1);

} else {
printf("Not
found.\n");

} return 0; } int match(char text[], char pattern[])


{ int c, d, e, text_length, pattern_length, position
= -1; text_length = strlen(text); pattern_length
= strlen(pattern); if (pattern_length > text_length)
{ return -1;

} for (c = 0; c <= text_length - pattern_length;


c++) { position = e = c; for (d = 0; d <
pattern_length; d++) { if (pattern[d] ==
text[e]) { e++; } else { break;

}} if (d ==
pattern_length) {
return position; }}
return -1;

OUTPUT:
Performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the C program implemented the string matching to created, executed and output
was verified successfully.

13
Ex.no:A.4(i)
INSERTION SORT
Date:

AIM:
To write a C program to implement the concept of insertion sort.
ALGORITHM:
Steps:
1. If it is the first element, it is already sorted.
2. Pick the next element.
3. Compare with all the elements in sorted sub-list.
4. Shift all the elements in sorted sub-list that is greater than the value to be sorted.
5. Insert the value.
6. Repeat until list is sorted.
PROGRAM:
#include <stdio.h>
void printArray(int array[], int size)
{
for (int i = 0; i < size; i++)

{
printf("%d ", array[i]);
}
printf("\n");
}
void insertionSort(int array[], int size)
{
for (int step = 1; step < size; step++)
{ int key =
array[step]; int j =
step - 1;
while (key < array[j] && j >= 0)
{
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
} } int
main()
{
int data[] = {9, 5, 1, 4, 3}; int size
= sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
printf("Sorted array in ascending order:\n");
printArray(data, size);
}

OUTPUT:

Performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the C program implemented Insertion sort executed and output was verified
successfully.

15
Ex.no:A.4(ii)
HEAP SORT
Date:

AIM:
To write a C program to implement the concept of heap sort.
ALGORITHM:
Step 1 - Construct a Binary Tree with given list of Elements.
Step 2 - Transform the Binary Tree into Min Heap.
Step 3 - Delete the root element from Min Heap using Heapify method.
Step 4 - Put the deleted element into the Sorted list.
Step 5 - Repeat the same until Min Heap becomes empty.
Program:
#include <stdio.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 arr[] =


{1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);
}
OUTPUT:

Performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the heap sort program was executed successfully.

17
Ex.no:B.1
BREADTH FIRST SEARCH
Date:

AIM:
To implement a graph traversal by using Breadth First Search.
ALGORITHM:
Steps
1. Start with the initial node.
2. Mark the initial node as visited and enqueue it.
3. While the queue is not empty:
• Dequeue a node from the queue.
• If the dequeued node is the goal node, stop the search.
• Otherwise, enqueue any successors (nodes that are directly connected to the dequeued
node) that have not yet been visited.
4. If the queue is empty, every node on the graph has been visited, or there is no path from
the initial node to the goal node.
5. If the goal node was found, return the path that was followed.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{ int vertex;
struct node *next;
};
struct Graph
{ int numVertices;
struct node **adjLists;
int *visited;
};
struct node *createNode(int v); struct Graph
*createGraph(int vertices); void addEdge(struct
Graph *graph, int src, int dest); void
printGraph(struct Graph *graph); void bfs(struct
Graph *graph, int startVertex); int isEmpty(struct
node *queue); void enqueue(struct node **queue,
int value); int dequeue(struct node **queue); void
printQueue(struct node *queue); struct node
*createNode(int v)
{
struct node *newNode = malloc(sizeof(struct node));
newNode->vertex = v; newNode->next = NULL;
return newNode;
}

struct Graph *createGraph(int vertices)


{
struct Graph *graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices; graph->adjLists =
malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++)
{
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
} return
graph; }
void addEdge(struct Graph *graph, int src, int dest)
{ struct node *newNode =
createNode(dest); newNode->next =
graph->adjLists[src]; graph->adjLists[src]
= newNode; newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
void printGraph(struct Graph *graph)
{
int v;
for (v = 0; v < graph->numVertices; v++)
{
struct node *temp = graph->adjLists[v];
printf("Adjacency list of vertex %d :", v);
while (temp)
{
printf("%d -> ", temp->vertex);
temp = temp->next; }printf("\n");}}
void bfs(struct Graph *graph, int startVertex)
{
struct node *queue = NULL; graph-
>visited[startVertex] = 1; enqueue(&queue,
startVertex);
while (!isEmpty(queue))
{
printQueue(queue); int currentVertex =
dequeue(&queue); printf("Visited %d ",
currentVertex); struct node *temp = graph-
>adjLists[currentVertex];
while (temp)
{

int adjVertex = temp->vertex;

if (graph->visited[adjVertex] == 0)
{
graph->visited[adjVertex] = 1;
enqueue(&queue, adjVertex);
}
temp = temp->next;
} }}
int isEmpty(struct node *queue)
{
return queue == NULL;
}
void enqueue(struct node **queue, int value)
{
struct node *newNode = createNode(value);
if (isEmpty(*queue))
{
*queue = newNode;
}
else
{
struct node *temp = *queue;
while (temp->next)
{
temp = temp->next;
}
temp->next = newNode;
}
}
int dequeue(struct node **queue)
{
if (isEmpty(*queue))
{
return -1; }
else
{
struct node *temp = *queue;
*queue = (*queue)->next;
int value = temp->vertex;
free(temp); return value;
}
}
void printQueue(struct node *queue)
{
struct node *temp = queue;
while (temp)
{

printf("%d ", temp->vertex);


temp = temp->next;
}
printf("\n"); }
int main(void)
{
printf("Enter number of vertices: ");
int vertices;
scanf("%d", &vertices);
struct Graph *graph = createGraph(vertices);
int choice;
do
{
printf("\nWhat do you want to do? \n");
printf(" 1. Add edge\n 2. Print graph\n 3. BFS\n 4. Exit\n");
printf("Enter your choice: "); scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter source and destination: ");
int src, dest;
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
break; case
2:
printGraph(graph);
break;
case 3:
printf("Enter starting vertex: ");
int startVertex;
scanf("%d", &startVertex);
bfs(graph, startVertex);
break;
case 4:
break;
default:
printf("Invalid choice");
}
}
while (choice != 4);
return 0;
}

Output:
Performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the implementation of graph traversal using BFS is executed successfully.
Ex.no:B.2
DEPTH FIRST SEARCH
Date:

AIM:
To implement graph traversal using Depth first search in c.

ALGORITHM:
1. Start by putting any one of the graph's vertices on top of a stack.
2. Take the top item of the stack and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited
list to the top of the stack.
4. Keep repeating steps 2 and 3 until the stack is empty.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a; struct
node *left;
struct node
*right;
};
void generate(struct node **,
int); void DFS(struct node *);
void delete(struct node **); int
main()
{ struct node *head = NULL;
int choice = 0, num, flag = 0,
key; do
{
printf("\nEnter your choice:\n1. Insert\n2. Perform DFS Traversal\n3. Exit\nChoice:
"); scanf("%d", &choice); switch(choice)
{
case 1:
printf("Enter element to insert: ");
scanf("%d", &num);
generate(&head,
num); break;
case 2: DFS(head);
break; case 3:
delete(&head);
printf("Memory Cleared\nPROGRAM
TERMINATED\n"); break; default:
printf("Not a valid input, try again\n");
}
} while (choice !=
3); return 0; }

void generate(struct node **head, int num)


{
struct node *temp = *head, *prev =
*head; if (*head == NULL)
{
*head = (struct node *)malloc(sizeof(struct node));
(*head)->a = num;
(*head)->left = (*head)->right = NULL;
}
else
{
while (temp != NULL)
{
if (num > temp->a)
{
prev = temp;
temp = temp->right;
}
else {
prev = temp;
temp = temp->left;
}
}
temp = (struct node *)malloc(sizeof(struct node));
temp->a = num;
if (num >= prev->a)
{
prev->right = temp;
}
else
{
prev->left = temp;
}

}
}
void DFS(struct node *head)
{ if
(head)
{
if (head->left)
{
DFS(head->left);
} if (head->right)
{
DFS(head->right);
}
printf("%d ", head->a);

}
}
void delete(struct node **head)
{
if (*head != NULL)
{
if ((*head)->left)
{
delete(&(*head)->left);
}
if ((*head)->right)
{
delete(&(*head)->right);
}
free(*head);
}
}

Output:
performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the implementation of graph traversal was executed successfully.
Ex.no:B.3
DIJKSTRA’S ALGORITHM
Date:

AIM:
To write a C program for implementing the graph for finding shortest path using Dijkstra’s
algorithm.

ALGORITHM:
STEPS
1.Start the program.
2.Mark the ending vertex with the distance of zero designate this vertex as current.
3.Find all the vertices leading to the current vertex. Calculate their distance to the end.
4.Mark the current vertex as visited
5.Mark the vertex with the smallest distance as current and repeated from step 3.
6.Stop the program.

PROGRAM:

#include<stdio.h>

#include<conio.h>

#define INFINITY 9999

#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int

startnode); int main() {

int G[MAX][MAX],i,j,n,u;

printf("Enter no. of vertices:");

scanf("%d",&n); printf("\nEnter the

adjacency matrix:\n");

for(i=0;i<n;i++) for(j=0;j<n;j++)

scanf("%d",&G[i][j]); printf("\nEnter

the starting node:");

scanf("%d",&u);
dijkstra(G,n,

u); return 0;

void dijkstra(int G[MAX][MAX],int n,int startnode)

int cost[MAX][MAX],distance[MAX],pred[MAX];

int

visited[MAX],count,mindistance,nextnode,i,j;

for(i=0;i<n;i++) for(j=0;j<n;j++)

if(G[i][j]==0) cost[i][j]=INFINITY;

else

cost[i][j]=G[i][j];

//initialize pred[],distance[] and

visited[] for(i=0;i<n;i++) {

distance[i]=cost[startnode][i];

pred[i]=startnode; visited[i]=0; }

distance[startnode]=0;

visited[startnode]=1; count=1;

while(count<n-1)

mindistance=INFINITY;
for(i=0;i<n;i++)

if(distance[i]<mindistance&&!visited[i])
{

mindistance=distance[

i]; nextnode=i;

//check if a better path exists through

nextnode visited[nextnode]=1;

for(i=0;i<n;i++)

if(!visited[i])

if(mindistance+cost[nextnode][i]<distance[i])

distance[i]=mindistance+cost[nextnode]

[i]; pred[i]=nextnode; }

count++; } for(i=0;i<n;i++) if(i!=startnode) {

printf("\nDistance of

node%d=%d",i,distance[i]);

printf("\nPath=%d",i);

j=i;

do {

j=pred

[j];

printf(

"<-

%d",j)

;
}while(j!=startnode);

OUTPUT:

performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:

Thus the above C program was verified and executed successfully.


Ex.no:B.4
PRIM’S ALGORITHM
Date:

AIM:

To write a C program to implement the undirected graph for finding the shortest path
using Prim’s algorithm.

ALGORITHM:

STEPS

1. Start the program.

2. Select a starting vertex.

3. Repeat step 4 and 5 until there are fringe vertices.

4. Select an edge ‘e’ connecting the tree vertex and fringe vertex that has minimum weight.

5.Add the selected edge and the vertex to the minimum spanning tree T.

6.Loop will execute atlast node.

7.Stop the pogram.

PROGRAM:

#include<stdio.h>

#include<stdlib.h>

#define infinity 9999 #define MAX 20 int

G[MAX][MAX],spanning[MAX][MAX],n;

int

prims();

int main()

{ int i,j,total_cost;

printf("Enter no. of

vertices:");

scanf("%d",&n);
printf("\nEnter the adjacency

matrix:\n"); for(i=0;i<n;i++)

for(j=0;j<n;j++)

scanf("%d",&G[i][j]);

total_cost=prims(); printf("\nspanning

tree matrix:\n"); for(i=0;i<n;i++) {

printf("\n"); for(j=0;j<n;j++)

printf("%d\t",spanning[i][j]);

} printf("\n\nTotal cost of spanning

tree=%d",total_cost); return 0; } int prims()

int cost[MAX][MAX]; int

u,v,min_distance,distance[MAX],from[MAX];

int visited[MAX],no_of_edges,i,min_cost,j;

//create cost[][] matrix,spanning[][]

for(i=0;i<n;i++) for(j=0;j<n;j++) {

if(G[i][j]==0) cost[i][j]=infinity;

else cost[i][j]=G[i][j]; spanning[i][j]=0; }

distance[0]=0; visited[0]=1;

for(i=1;i<n;i++) { distance[i]=cost[0][i];

from[i]=0; visited[i]=0; } min_cost=0;

//cost of spanning tree no_of_edges=n-1;

//no. of edges to be added

while(no_of_edges>0)
{ min_distance=infinity; for(i=1;i<n;i++)

if(visited[i]==0&&distance[i]<min_distac

e)

{ v=i;

min_distance=distance

[i];

u=from[v];

spanning[u][v]=distance[v];

spanning[v][u]=distance[v];

no_of_edges--; visited[v]=1;

//updated the distance[] array

for(i=1;i<n;i++)

if(visited[i]==0&&cost[i][v]<distance[i])

distance[i]=cost[i]

[v]; from[i]=v; }

min_cost=min_cost+cost[u][v];

return(min_cos

t);

}
Output:

performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:

Thus finding minimum cost of spanning tree using prims algorithm was executed
successfully.
Ex.no:B.5
FLOYD’S ALGORITHM
Date:

AIM:
To implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.

ALGORITHM:

Step 1: Initialize the shortest paths between any 2 vertices with Infinity.
Step 2: Find all pair shortest paths that use 0 intermediate vertices, then find the shortest
paths that use 1 intermediate vertex and so on.. until using all N vertices as intermediate
nodes.
Step 3: Minimize the shortest paths between any 2 pairs in the previous operation.
Step 4: For any 2 vertices (i,j) , one should actually minimize the distances between this pair
using the first K nodes, so the shortest path will be: min(dist[i][k]+dist[k][j],dist[i][j]).

PROGRAM:
#include <stdio.h>
#include <stdlib.h>

void floyd(int **graph, int n)


{
int i, j, k;
for (k = 0; k < n; k++)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (graph[i][j] > graph[i][k] + graph[k][j])
graph[i][j] = graph[i][k] + graph[k][j];
}
}

}
}

int main(void)
{
int n, i, j;
printf("Enter the number of vertices: ");
scanf("%d", &n);
int **graph = (int **)malloc((long unsigned) n * sizeof(int *));
for (i = 0; i < n; i++)
{
graph[i] = (int *)malloc((long unsigned) n * sizeof(int));
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{ if (i == j)
graph[i][j] = 0;
else
graph[i][j] = 100;
}
} printf("Enter the
edges: \n"); for (i = 0; i <
n; i++)
{
for (j = 0; j < n; j++)
{
printf("[%d][%d]: ", i, j);
scanf("%d", &graph[i][j]);
}
}
printf("The original graph is:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", graph[i][j]);
}
printf("\n");
} floyd(graph, n); printf("The
shortest path matrix is:\n"); for (i =
0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", graph[i][j]);
}
printf("\n");
} return 0;
}

OUTPUT:
performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the implementation of Floyd algorithm for finding all pair shortest path program
was executed successfully.
Ex.no:B.6
WARSHALL’S ALGORITHM
Date:

AIM:
To compute the transitive closure of a directed graph using Warshall's algorithm.

ALGORITHM:

Step 1: Initialize the shortest paths between any 2 vertices with Infinity.

Step 2: Find all pair shortest paths that use 0 intermediate vertices, then find the shortest
paths that use 1 intermediate vertex and so on.. until using all N vertices as intermediate
nodes.

Step 3: Minimize the shortest paths between any 2 pairs in the previous operation.

Step 4: For any 2 vertices (i,j) , one should actually minimize the distances between this pair

using the first K nodes, so the shortest path will be: min(dist[i][k]+dist[k][j],dist[i][j]).

PROGRAM:

#include<stdio.h>
#include<conio.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");
}
getch();
}
OUTPUT:
performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the implementation of warshall’s algorithm was executed successfully.
Ex.no:C.1
DIVIDE AND CONQUER ALGORITHM
Date:

Aim:

To implement a C program for finding the maximum and minimum number in a given list of
n numbers using the divide and conquer techniques.

Algorithm:

1.Start by dividing the given problem.


2.Into subprogram using recursion.
3.Conquer to solve the smaller subprograms recursively if the subprogram is small
enough to solve it directly.
4.combining the solutions of the subprogram that are the part of the recursively
process to solve the actual problem.
5. Stop the program.

Program:
#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];
}
els
e
{
if(i == j-1)
{
if(a[i] <a[j])
{ max
= a[j];
min = a[i];
} else
{ max =
a[i];
min = a[j];

}
}
el
se
{
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:
performance 20

Program 40

Result 20

Record 20

Total 100

Result:
Thus the above C program was verified and executed successfully.
Ex.no:C.2a
QUICK SORT
Date:

AIM:
To write a C program to implement the concept of quick sort.

ALGORITHM:

1.Pick: Select an element.


2.Divide: Split the problem set, move smaller parts to the left of the pivot and larger items to
the right.
3.Repeat and combine: Repeat the steps and combine the arrays that have previously been
sorted.

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

// function to find the partition position


int partition(int array[], int low, int high) {

// select the rightmost element as


pivot int pivot = array[high];

// pointer for greater element


int i = (low - 1);

// traverse each element of the


array // compare them with the
pivot for (int j = low; j < high;
j++) { if (array[j] <= pivot) {

// if element smaller than pivot is found


// swap it with the greater element pointed by i
i++;

// swap element at i with element at j


swap(&array[i], &array[j]);
}
}
// swap the pivot element with the greater element at i
swap(&array[i + 1], &array[high]);

// return the partition point


return (i + 1);
}

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


{ if (low < high) {

// find the pivot element such that


// elements smaller than pivot are on left of
pivot // elements greater than pivot are on right
of pivot int pi = partition(array, low, high);

// recursive call on the left of pivot


quickSort(array, low, pi - 1);

// recursive call on the right of pivot


quickSort(array, pi + 1, high);
}
}

// function to print array elements


void printArray(int array[], int
size) { for (int i = 0; i < size; ++i)
{ printf("%d ", array[i]);
}
printf("\n");
}

// main
function int
main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};

int n = sizeof(data) / sizeof(data[0]);

printf("Unsorted Array\n");
printArray(data, n);

// perform quicksort on data


quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \n");


printArray(data, n);
}
OUTPUT:

performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the implementation of quick sort was executed successfully.
Ex.no:C.2c

Date: Merge sort

Aim:
To write a C program to implement the concept of merge sort.
Algorithm:

STEP 1:Start the program.


STEP 2:First divide the number of elements by 2 and separate them as two.
STEP 3:Divide these two which are divided by 2.
STEP 4:Until you get a single element.
STEP 5:Start comparing the starting two pair of elements with each other and place them
in ascending order.
STEP 6:When you combine them compare them so that you make sure the sorted
elements.
STEP 7:When all the elements are compared the array will be surely sorted in an
ascending order.
STEP 8:Stop the program.
Program:

#include <stdio.h>

void merge(int arr[], int p, int q, int

r) { int n1 = q - p + 1; int n2 = r -

q;

int L[n1], M[n2]; for

(int i = 0; i < n1; i++)

L[i] = arr[p + i]; for

(int j = 0; j < n2; j++)

M[j] = arr[q + 1 + j];


int i,

j,k;

i = 0;

j = 0;

k = p;

while (i < n1 && j < n2)

{ if (L[i] <= M[j]) {

arr[k] =

L[i]; i++;

} else {

arr[k] = M[j];

j++; }

k++; }

while (i < n1)

arr[k] = L[i];

i++; k++;

while (j < n2) { arr[k] = M[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 arr[], int size)
{ for (int i = 0; i < size; i++)

printf("%d ", arr[i]); printf("\n");


} int main() { int arr[] = {6, 5,

12, 10, 9, 1}; int size =

sizeof(arr) / sizeof(arr[0]);

mergeSort(arr, 0, size - 1);

printf("Sorted array: \n");

printArray(arr, size);

OUTPUT:

performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:

Thus the C program implemented Merge sort executed and output was verified
successfully.
Ex.no:D.1
N-QUEEN PROBLEM USING BACKTRACKING
Date:

Aim:
To implement a C program for N Queens problem using Backtracking.

Algorithm:
1.Start the program,.
2.Initialize an empty chessboard of size NxN.
3.Start with the leftmost column and place a queen in the first row of that column.
4.Move to the next column and place a queen in the first row of that column.
5.Repeat step 4 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.
6.If all N queens have been placed, print the solution.
7.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.
8.Remove the queen from the previous column and move it down one row.
9.Repeat steps 5-8 until all possible.
10.Stop.
Program:
#define N 4
#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;

/* Check this row on left side */


for (i = 0; i < col;
i++) if
(board[row][i])
return false;

/* Check upper diagonal on left side */


for (i = row, j = col; i >= 0 && j >= 0; i--, j-
-) if (board[i][j])
return false;
/* Check lower diagonal on left side */
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)) {
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 } };

if (solveNQUtil(board, 0) == false)
{
printf("Solution does not exist");
return false;
}

printSolution(board
); return true; }
int main() {
solveNQ();
return 0; }

Output:
performance 20

Program 40

Result 20

Record 20

Total 100

Result:
Thus the above C program was verified and executed successfully.
Ex.no:E.1
Kth SMALLEST NUMBER
Date:

AIM:
To implement randomized algorithm for finding Kth smallest number.

ALGORITHM:

1.Select a random element from a array as a pivot.


2.Then partition to the array around the pivot, its help to all the smaller element were placed
before in the pivot and all greater element are placed after the pivot.
3.Then Check the position of the pivot. If it is the kth element then return it.
4.If it is the less than the kth element then repeat the process of the subarray.
5.If it is the greater then the kth element then repeat the process of the left subarray.

PROGRAM:
#include<stdio.h>
#include<math.h>
#include<time.
h>
#include<stdlib
.h> int N = 20;
int A[20];
void swap(int dex1, int
dex2) { int temp =
A[dex1]; A[dex1] =
A[dex2];
A[dex2] = temp;
}

int partition(int start, int end) {


int i = start + 1;
int j = i; int pivot =
start; for (; i < end;
i++) { if (A[i] <
A[pivot]) {
swap(i, j);
j++;
} }
if (j <=
end)
swap(pivot, (j - 1));

return j - 1;
}

void quick_sort(int start, int end, int


K) { int part; if (start < end) {
part = partition(start,
end);

if (part == K - 1)
printf("kth smallest element : %d ", A[part]);
if (part > K - 1)
quick_sort(start, part, K);
else
quick_sort(part + 1, end, K);
}
return;
}

int main(int argc, char **argv)


{ int i;
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);

for (i = 0; i < N; i++)


A[i] = rand() % (1000 - 1 + 1) + 1;

printf("The original sequence is: ");


for (i = 0; i < N; i++)
printf("%d ", A[i]);

printf("\nEnter the Kth smallest you want to find:


"); int k;
scanf("%d", &k);
quick_sort(0, N, k);
}

OUTPUT:
performance 20

Program 40

Result 20

Record 20

Total 100

RESULT:
Thus the implementation of randomized algorithm fo finding kth smallest number was
executed successfully.
Ex.no:E.2
TRAVELLING SALESMAN PROBLEM
Date:

AIM:
To implement a C program for finding the optimal solution for travelling salesperson
problem.

ALGORITHM:
1.Start the program.
2.Consider city 1 as the starting and ending point.
3.Generate all (n-1)! Permutations of cities.
4.Calculate the cost every permutations and keep tracks of the minimum cost
permutations.
5.Return the permutation with minimum cost.
6.Stop the program.

PROGRAM:
#include <stdio.h>
int matrix[25][25], visited_cities[10], limit, cost =
0; int tsp(int c)
{ int count, nearest_city =
999; int minimum = 999,
temp;
for(count = 0; count < limit; count++)
{
if((matrix[c][count] != 0) && (visited_cities[count] == 0))
{
if(matrix[c][count] < minimum)
{
minimum = matrix[count][0] + matrix[c][count];
}
temp = matrix[c][count];
nearest_city = count;
}
}
if(minimum != 999)
{ cost = cost +
temp;
}
return nearest_city;
}
void minimum_cost(int city)
{ int nearest_city;
visited_cities[city] =
1; printf("%d ", city
+ 1); nearest_city =
tsp(city);

if(nearest_city ==
999)
{
nearest_city =
0;

printf("%d", nearest_city + 1);


cost = cost + matrix[city][nearest_city];
return;
}
minimum_cost(nearest_city);
} int
main()
{
int i, j;
printf("Enter Total Number of
Cities:\t"); scanf("%d", &limit);
printf("\nEnter Cost Matrix\n"); for(i
= 0; i < limit; i++)
{
printf("\nEnter %d Elements in Row[%d]\n", limit, i + 1);
for(j = 0; j < limit; j++)
{
scanf("%d", &matrix[i][j]);
}
visited_cities[i] = 0;
}
printf("\nEntered Cost Matrix\n");
for(i = 0; i < limit; i++)
{ printf("\n"); for(j
= 0; j < limit; j++)
{
printf("%d ", matrix[i][j]);
} } printf("\n\nPath:\t");
minimum_cost(0);
printf("\n\nMinimum Cost:
\t"); printf("%d\n", cost);
return 0;
}
Output:

performance 20

Program 40

Result 20

Record 20

Total 100
RESULT:

Thus the above C program was verified and executed successfully.

You might also like