Professional Documents
Culture Documents
Algorithm CS3401 5 2 59
Algorithm CS3401 5 2 59
Algorithm CS3401 5 2 59
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:
ALGORITHM:
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.
PROGRAM:
#include
<stdio.h>
#include<time.h
> int main()
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++)
{
printf("%d is present at location %d.\n", search, c+1);
break;
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:
ALGORITHM:
STEP 2: get the header file and the inputs and read the search element from the user.
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.
PROGRAM
#include <stdio.h>
int start_index,
int end_index,
int element){
if (array[middle] == element)
return middle;
} return -1;}
int main(void){
else
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:
ALGORITHM:
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.
PROGRAM:
#include <stdio.h>
#include <string.h> int
match(char [], char []);
int main() {
char a[100],
b[100]; int
position;
11
if (position != -1)
{ printf("Found at location: %d\n", position
+ 1);
} else {
printf("Not
found.\n");
}} 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 (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}
heapSort(arr, n);
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;
}
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)
{
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 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 MAX 10
int G[MAX][MAX],i,j,n,u;
adjacency matrix:\n");
for(i=0;i<n;i++) for(j=0;j<n;j++)
scanf("%d",&G[i][j]); printf("\nEnter
scanf("%d",&u);
dijkstra(G,n,
u); return 0;
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];
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;
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; }
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:
AIM:
To write a C program to implement the undirected graph for finding the shortest path
using Prim’s algorithm.
ALGORITHM:
STEPS
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.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
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
printf("\n"); for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
for(i=0;i<n;i++) for(j=0;j<n;j++) {
if(G[i][j]==0) cost[i][j]=infinity;
distance[0]=0; visited[0]=1;
for(i=1;i<n;i++) { distance[i]=cost[0][i];
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;
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>
}
}
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:
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
=
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:
PROGRAM:
#include <stdio.h>
void swap(int *a, int
*b) {
int t =
*a; *a =
*b;
*b = t;
}
// main
function int
main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};
printf("Unsorted Array\n");
printArray(data, n);
performance 20
Program 40
Result 20
Record 20
Total 100
RESULT:
Thus the implementation of quick sort was executed successfully.
Ex.no:C.2c
Aim:
To write a C program to implement the concept of merge sort.
Algorithm:
#include <stdio.h>
r) { int n1 = q - p + 1; int n2 = r -
q;
j,k;
i = 0;
j = 0;
k = p;
arr[k] =
L[i]; i++;
} else {
arr[k] = M[j];
j++; }
k++; }
arr[k] = L[i];
i++; k++;
if (l < r) { int m = l
+ (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1,
}}
void printArray(int arr[], int size)
{ for (int i = 0; i < size; i++)
sizeof(arr) / sizeof(arr[0]);
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");
}
}
return true;
}
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:
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;
}
return j - 1;
}
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;
}
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;
performance 20
Program 40
Result 20
Record 20
Total 100
RESULT: