Algorithm-Lab Updated
Algorithm-Lab Updated
EXP.NO: 1
IMPLEMENTATION OF LINEAR
SEARCH
DATE:
AIM:
To write a C program for “implementation of linear search”.
ALGORITHM:
1. Start the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
#define max20
int pos;
int Linearsearch(int,int[],int);
void main()
{
Int ch=1;
double t;
int n,i,k,op,pos,a[20];
Clock_t begin,end;
Clrscr();
While(ch)
{
Printf(“\n….MENU……\n1.Linearsearch\n2.Exit\n”);
Scanf(“%d”,&op);
Switch(op)
{
case1:
Printf(“\n enter the number of elements\n”);
Scanf(“%d”,&n);
for(i=0;i<n;i++)
Scanf(“%d”,&a[i]);
lOMoARc PSD|28104798
lOMoARc PSD|28104798
if(pos==-1)
printf(“\n\n unsuccessful search”);
else
printf(“element %d is found at position %d”,k,pos+1);
printf(“\n Time taken is %if CPU cycles\n”,(end_begin)/CLK_TCK);
getch();
break;
default:
exit(0);
}
Printf(“\n Do you wish to run again(1/0)\n”);
Scanf(“%d”,&ch);
}
getch();
}
int Linearsearch(int n,int a[],int k)
{
delay(1000);
If(n<0)
return -1;
if(k==a[n1])
return(n-1);
else
return Linearsearch(n-1,a,k);
}
lOMoARc PSD|28104798
OUTPUT:
….MENU….
1.Linearsearch
2.Exit
Enter your choice : 1
Enter the number of elements 3
Enter the number of an array in the order25 69 98
Enter the elements to be searched 98
Element 98 is found atposition 3
Time taken is 1.978022CPU cycles
Value of n Time
3 1.978022
4 2.032967
6 3.956044
8 1.978022
10 3.021978
12 8.956044
14 10.12345
15
10
Value of n Time
Linearsearch
lOMoARc PSD|28104798
RESULT:
Thus the C program “Implementation of Linear search” has been executed successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX:NO:2
IMPLEMENT RECURSIVE BINARY SEARCH. DETERMINETHETIME
REQUIRED TO SEARCH AN ELEMENT.
DATE:
AIM:
To implement a recursive binary search program and determine the time requiredtosearch an element.
ALGORITHM:
1. start the program.
2. Set the low index to the first element of the array and the high index tothe lastelement.
3. Set the middle index to the average of the low and high indices.
a. If the element at the middle index is the target element, return themiddleindex.
b. Otherwise, based on the value of the key to be found and the valueof themiddle
element, decide the next search space.
i. If the target is less than the element at the middle index, set thehighindex to
middle index – 1.
ii. If the target is greater than the element at the middle index, set thelowindex to
middle index + 1.
4. Perform step 2 repeatedly until the target element is found or the searchspace isexhausted.
5. And also calculate the time complexity.
6. Stop the program.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#define MAX 20
int pos;
int binsearch(int,int[],int,int,int);
void main()
{
int ch=1;
doublet;
int n,i,a[20],e,low,high,pos;
clock_tbegin,end;
clrscr();
printf("Enter The Size Of TheArray:");
scanf("%d",&n);
printf("Enter The Elements Of the Array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter The Element To Search");
scanf("%d",&e);
low=0;high=n-1;
begin=clock();
pos=binsearch(n,a,e,low,high);
end=clock();
pos=binsearch(n,a,e,low,high);
end=clock();
if(pos==-1)
printf("Unsuccessfull Search");
else
printf("Element %d found at pos %d",e,pos+1);
printf("\ntime taken is %f if cpu1 cycles",(end-begin)/CLK_TCK);
getch();
}
int binsearch(int n,int a[],int e,int low,int high)
{
int mid; delay(1000);
mid=(low+high)/ 2;
if(low>high)
return -1;
if(e==a[mid])
return(mid);
else
if(e<a[mid])
lOMoARc PSD|28104798
OUTPUT:
search:1Element 1 is foundat 0
return binsearch(n,a,e,low,mid-1);
else
return binsearch(n,a,e,mid+1,high);
}
lOMoARc PSD|28104798
1 1.944
2 2.967
3 0.989
4 3.021
lOMoARc PSD|28104798
RESULT:
The c program to implement the recursive binary search has been executedsuccessfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EXP.NO: 3
FUNCTION SEARCH
DATE:
AIM:
The Aim of this function is to search for all occurrences of a given pattern within given text and print the
indices where the pattern is found
ALGORITHM:
Step 1: Start
Step 2: Loop through the text from index 0 to n-m, where n is the length of thetext and m is the
length of the pattern.
Step 3: For each iteration, check if the substring of text from the current indexto current index +
pattern length is equal to the pattern.
Step 4 : If there's a match, print the index where the pattern is found.
Step 5: Continue looping until all occurrences of the pattern in the text are found
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include<stdio.h>
#include<string.>
#include<time.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
else
{
int main()
{
char txt[]="AABAACAADAABAAABAA";
char pat[]="AABA";
printf("Text: %s\n",txt);
printf("Pattern:%s\n",pat);
printf("Occurences:\n");
search(pat,txt);
printf("Time Complexity:O(56)");
getch();
}
lOMoARc PSD|28104798
OUTPUT:
Text: AABAACAADAABAAABAA
Pattern:
AABA
Occurrences:
Pattern found at index
0Pattern found at index
9Pattern found at index 13
Total occurrences: 3Time complexity:O(56)
lOMoARc PSD|28104798
RESULT:
The function search() takes a pattern and a text as input and searches for all occurrences of the
pattern in the text. It then prints the indices where the pattern is found. In the example usage, the
pattern "Abab" Is found at indices0 and 10 in the text "Ababdabacdababcabab"
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EXP.NO: 4(a)
INSERTION SORT
DATE:
AIM:
To write a C program to sort the elements using insertion sort and plot a graphfor the time taken.
ALGORITHM :
1. Start
2. Declare the variables.
3. Get the value of n from the user.
7. 7.Stop
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void insertion(int a[],int n)
{
int i,key,j;
for(i=1;i<n;i++)
key=a[i];
j=i-1;
while(j>=0&&a[j]>key)
a[j+1]=a[j];
j=j-1;
}
a[j+1]=key;
}
}
{
int main()
{
int a[50],i,n;
clock_t t;
double time;
t=clock();
printf("enter n\n ");
scanf("%d",&n);
printf("enter elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
insertion(a,n);
t=clock()-t;
printf("sorted elements\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
time=((double)t)/CLOCKS_PER_SEC;
printf("time taken %f sec",time);
return 0;}
lOMoARc PSD|28104798
OUTPUT:
Enter
n3
Enter
elements12234
2
Sorted
elements234
122
Time taken 11.098901 sec
GRAPH:
20
18
16
14
12
10 Series1
Series2
1 2 3 4 5 6
lOMoARc PSD|28104798
RESULT:
Thus the program for insertion sort has been executed successfully along with the time complexity graph.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EXP.NO: 4(b)
HEAP SORT
DATE:
AIM:
To write a c program to sort a set of elements using heap sort and plot a graph of the time taken .
ALGORITHM:
1. start the program
2. declare the variables and functions.
3. get the value of n and elements of the array.
4. using the heapify() function find the larger value and sort them by usingheapsort()function.
5. display the sorted elements and time taken inseconds.
6. 6.stop the program.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include<stdio.h>
#include<time.h>
Void heapify(int*,int,int);
Voidprint_array(int*,int);
int main()
{
int n,i,a[50];
clock_t t;
double time;
t=clock();
printf("enter the value of n\n");
scanf("%d,&n);
printf("\n enter elements\n");
for(i=0;i<n;i++)
{
scanf("\n %d",&a[i]);
}
heapsort(a,n);
printf("\n\n aftersorting\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
t=clock()-t;
time=((double)t)/CLOCK_PER_SEC;
printf("time taken is %f",time);
return 0;
}
void heapsort(int * a,int n)
{
int i;
for(i=n-1;i>=0;i--)
{
heapify(a,n,i);
}
for(i=n-1;i>=0;i--)
{
int temp=a[i];
a[i]=a[0];
a[0]=temp;
heapify(a,i,0);
lOMoARc PSD|28104798
lOMoARc PSD|28104798
}
void heapify(int*a,int n,int i)
{
int large=i;
int left=2*i+1;
int right=2*i+2;
if(left<n&&a[left]>a[large])
{
large=left;
}
if(right<n&&a[right]>a[large])
{
large=right;
}
if(large!=i)
{
int temp=a[i];
a[i]=a[large];
a[large]=temp;
heapify(a,n,large);
}
}
void print_array(int *a,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
lOMoARc PSD|28104798
OUTPUT:
Enter n:5
Enter
element2
345
2
3
67
After sort:
2
3
23
45
67
Time taken:11.703297sec
GRAPH:
20
18
16
14
12
10 Series1
Series2
1 2 3 4 5 6
lOMoARc PSD|28104798
RESULT:
Thus the program for heap sort has been executed successfully along with the timecomplexity graph.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX. NO : 5(a)
BREADTH FIRST SEARCH
DATE:
AIM:
To develop a program to implement graph traversal using breadth first search.
ALGORITHM :
1. Start by putting any one of the graph's vertices at the back of a queue
2. Take the front item of the queue 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 back of the
queue.
4. Keep repeating steps 2 and 3 until the queue is empty.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v)
{
for (i=1;i<=n;i++)
if(a[v][i] &&!visited[i])
q[++r]=i;
if(f<=r)
{
visited[q[f]]=1;
bfs(q[f++]);
}
}
void main ( )
{
int v;
clrscr();
printf("\n Enter the number ofvertices:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrixform:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachableare:\n");
for (i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i);
else
printf("\n Bfs is notpossible");
getch();
}
lOMoARc PSD|28104798
OUTPUT:
RESULT:
Thus to develop a program to implement a graph traversal using breadth firstsearch has been executed
successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX. NO : 5(b)
DEPTH FIRST SEARCH
DATE:
AIM:
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.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[20] [20] , reach[20] ,n;
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
if(a[v][i] &&!reach[i])
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main( )
{
inti,j,count=0;
clrscr();
printf("\n Enter number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
reach[i]=0;
for (j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for (i=1;i<=n;i++)
{
if(reach[i]
)
count++;
}
if(count==n)
printf("\n Graph is connected");
else
printf("\n Graph is notconnected");
getch();
}
lOMoARc PSD|28104798
OUTPUT:
Graph is connected
lOMoARc PSD|28104798
RESULT:
Thus to develop a program to implement graph traversal using depth first searchhas been executed
successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX. NO : 6(a)
DIJKSTRA’S ALGORITHM
DATE:
AIM:
To develop a program for shortest paths to other vertices using Dijkstra's algorithm.
ALGORITHM:
1. Create a set short path to store vertices that come in the way of the shortest path tree.
2. Initialize all distance values INFINITE and assign distance values as 0 for source vertex so
that it is picked first.
3. Loop until all vertices of the graph are in the short path.
4. Take a new vertex that is not visited and is nearest.
5. Add this vertex to short path .
6. For all adjacent vertices of this vertex update distance. Now check every adjacent vertex of
V, if sum of distance of u and weight of edge is else the update it.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include<conio.>
#include<limits.>
#include <stdbool.h>
#include<stdio.h>
#define V 9
return min_index;
}
void printSolution(int dist[])
{
int dist[V];
boolsptSet[V]:
dist[src] = 0;
{
lOMoARc PSD|28104798
lOMoARc PSD|28104798
sptSet[u]= true;
if(!sptSet[v]&&graph[u][v]&&dist[u]!=INT_MAX&&dist[u]+graph[u][v]<dist [v])
printSolution(dist);
int main()
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph,0);
getch();
return 0;
}
lOMoARc PSD|28104798
GRAPH:
OUTPUT:
lOMoARc PSD|28104798
RESULT:
Thus the program for develop the shortest paths to other vertices using dijkstra’salgorithm has been
executed successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX. NO : 6(b)
PRIMS’S ALGORITHM
DATE:
AIM
To write the program for minimum cost spanning tree of a given undirected graph
using prims algorithm.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<limits.h>
#include<stdbool.h>
#defineV 5
int key[V];
bool mstSet[V];
printMST(parent, graph);
}
lOMoARc PSD|28104798
lOMoARc PSD|28104798
int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };
primMST(graph);
getch();
Return 0;
}
lOMoARc PSD|28104798
GRAPH:
OUTPUT:
lOMoARc PSD|28104798
RESULT:
Thus the program for find the minimum cost spanning tree using prim’s algorithm has been executed
successefully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX. NO : 7(A)
FLOYD’S ALGORITHM
DATE:
Aim:
Algorithm:
PROGRAM:
#include <stdlib.h>
void floydWarshall(int **graph, int n)
{
int i, j, k;
for (k = 0; k < n; k++)
{
int main(void)
{
int n, i, j;
int**graph=(int**)malloc((long unsigned)n*sizeof(int*));
printf(“Enter the number of vertices: “);
Output:
Enter the number of vertices: 4
Enter the edges:
[0][0]: 2
[0][1]: 4
[0][2]: 5
[0][3]: 6
[1][0]: 1
[1][1]: 0
[1][2]: 0
[1][3]: 4
[2][0]: 4
[2][1]: 7
[2][2]: 8
[2][3]: 9
[3][0]: 0
[3][1]: 5
[3][2]: 8
[3][3]: 9
2456
1004
lOMoARc PSD|28104798
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”);
}
floydWarshall(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;
}
lOMoARc PSD|28104798
4789
0589
1004
4779
0446
lOMoARc PSD|28104798
Result:
Thus to implement floyd’s algorithm for all pairs shortest path problem has beenhas been executed
successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX.NO: 7(B)
WARSHALL’S ALGORITHM
DATE:
Aim:
To compute the transitive closure of a directed graph using warshall
algorithm.
Algorithm:
1. Start the program
2. Initialize the variables and graph
Here we use warshall algorithm to compute the transitive closure of the directed graph
Program:
#include<stdio.h>
const int MAX = 100;
void WarshallTransitiveClosure(int graph[MAX], int numVert);int main(void)
{
int I,j,numVert;
int graph[100][100];
printf(“Enter the number of vertices:”);
scanf(“%d”,&numVert);
printf(“Enter the adajacency matrix:-\n”);
for(i=0;i<numVert;i++) for(j=0;j<numVert;j++);
scanf(“%d”,&graph[i][j]);
WarshallTransitiveClosure(graph,numVert);
{
for(i=0;i<numvert;i++)
{
for(j=0;j<numVert;j++)
{
if(graph[i][j] || (graph[i][k]&&graph[k][j]))
graph[i][j]=1;
}
}
}
}
lOMoARc PSD|28104798
OUTPUT:
adjacency Matrix:- 1 0 0 0
1001
1100
1100
1010
1 0 0 0
1 1 1 1
1 1 1 1
lOMoARc PSD|28104798
RESULT:
Thus to compute the transitive closure of the directed graph usingwarshall algorithm has been
executed successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX.NO: 8
DIVIDE AND CONQUER TECHNIQUE
DATE:
AIM:
To find the maximum and minimum numbers in given list of n numbersusing divide and
conquer technique
ALGORITHM:
5. If the array is 2 elements long if arr[0] > arr[1], return [arr[1], arr[0]]
7. Split the array roughly into a left hald, calling minmax on each half
PROGRAM
#include<stdio.h>
struct pair
{
Int min;
Int max;
};
Struct pair getMinMax(int arr[], int n)
{
Struct pair minmax;Int I;
If (n == 1)
{
Minmax.max = arr[0];
Minmax.min = arr[0];
Return minmax;
}
If (arr[0] > arr[1])
{
Minmax.max = arr[0];
Minmax.min = arr[1];
}
Else
{
Minmax.max = arr[1];
Minmax.min = arr[0];
}
For (I = 2; i<n; i++)
{
If (arr[i] > minmax.max) Minmax.max = arr[i];
Else if (arr[i] < minmax.min) Minmax.min = arr[i];
}
Return minmax;
}
Int main()
{
Int arr[] = {1000, 11, 445, 1, 330, 3000};
Int arr_size = 6;
Struct pair minmax = getMinMax (arr, arr_size);
Printf(“nMinimum element is %d”, minmax.min);
Printf(“nMaximum element is %d”, minmax.max);
Getchar();
Return 0;
}
lOMoARc PSD|28104798
OUTPUT:
nMinimum Element is 1
RESULT:
Thus the program for finding maximum and minimum number of nnumbers using
divide and conquer technique was executed successfully
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX.NO: 9(a)
MERGE SORT
DATE:
AIM:
ALGORITHM:
3. Find the middle index of the array to divide int two half
4. Find mid=(left+right)/2
7. Stop
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include <stdio.h>
#include <time.h>
// Function to merge two sorted arrays
void merge(int arr[], int left[], int left_size, int right[], int right_size)
{
int i = 0, j = 0, k = 0;
while (i < left_size && j < right_size)
{
if (left[i] < right[j])
arr[k++] = left[i++];
else
arr[k++] = right[j++];
}
while (i < left_size) arr[k++] = left[i++];
while (j < right_size) arr[k++] = right[j++];
}
// Function to perform merge sortvoid
mergeSort(int arr[10], int n)
{
if (n <= 1) return;
int mid = n / 2;
int left[10];
int right[20];
// Dividing the array into left and right halves
for (int i = 0; i < mid; i++)
left[i] = arr[i];
for (int i = mid; i < n; i++)
right[i - mid] = arr[i];
// Recursively sorting left and right halvesm
mergeSort(right, n - mid);
// Merging the sorted left and right halves
merge(arr, left, mid, right, n - mid);
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[10];
printf("Enter the elements: ");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("\nOriginal Array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]); printf("\n");
// Recording the start time
clock_t start = clock();
mergeSort(arr, n);
// Recording the end time
clock_t end = clock();
printf("\nSorted Array: ");
lOMoARc PSD|28104798
lOMoARc PSD|28104798
mergeSort(right, n - mid);
// Merging the sorted left and right halves
merge(arr, left, mid, right, n -mid);
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[10];
printf("Enter the elements: ");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("\nOriginal Array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]); printf("\n");
// Recording the start time
clock_t start = clock();
mergeSort(arr, n);
// Recording the end time
clock_t end = clock();
printf("\nSorted Array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]); printf("\n");
// Calculating the time taken to sort
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("\nTime taken to sort: %f seconds\n", time_taken);
return 0;
}
lOMoARc PSD|28104798
OUTPUT:
the elements: 28 41 47
Original array: 28 41 47
Sorted array: 28 41 47
RESULT:
Thus to implement a merge sort to sort an array elements hasbeen executed successfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX.NO: 9(b)
QUICK SORT
DATE:
AIM:
ALGORITHM:
2. Declare an array
7. Stop
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include<stdio.h>
#include<stblib.h>
#include<time.h>
void swap(int*a, int*b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int partition(int arr[],int low,int high)
{
int pivot=arr[low];
int i=low+1;int
j=high; while(1)
{
while(i<=j&&arr[i]<pivot)
i++;
while(i<=j&&arr[j]>pivot)
j--;
if(i<=j)
{
swap(&arr[i],&arr[j]);
i++;
j--;
}
else
break;
}
swap(&arr[low],&arr[j]);
return j;
}
void quicksort(int arr[],int low,int high)
{
if(low<high)
{
int pivotIndex=partition(arr,low,high);
}
}
int main()
{
int n;
printf(“Enter the number of elements:”);
scanf(“%d”,&n);
int arr[10];
stand(time(0)); for(int
i=0;i<n;i++)
{
arr[i]=rand()%100;
lOMoARc PSD|28104798
lOMoARc PSD|28104798
}
printf(“Original array:\n”);
for(int i=0;i<n;i++)
{
printf(“%d”,arr[i]);
}
clock_t start=clock();
double time_taken=((double)(end-start))
printf(“\nSorted array:\n);
for(int i=0;i<n;i++)
{
printf(“%d”,arr[i]);
}
printf(“\nTime taken:%.2f ms\n”,time_taken);
return 0;
}
lOMoARc PSD|28104798
OUTPUT:
Original array:
60 56 27 20 77 9
Sorted array:
9 20 27 56 60 77
RESULT:
Thus the quick sort to sort an array of element has been executedsuccessfully.
lOMoARc PSD|28104798
lOMoARc PSD|28104798
EX.NO: 10
N-QUEENS PROBLEM USING
DATE: BACKTRACKING
AIM:
ALGORITHM:
2. Start with the leftmost column and place a queen in the first row of thatcolumn
3. Move to the next column and place a queen in the first row of thatcolumn
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 therules of the problem
7. Remove the queen from the previous column and move it down onerow
8. Repeat steps 4-7 until all possible configurations have been tired
lOMoARc PSD|28104798
lOMoARc PSD|28104798
PROGRAM:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int board[20],count;
void print(int n)
{
int i,j;
printf(“\n\nSolution %d:\n\n”,++count);
for(i=1;i<=n;++i)
printf(“\t%d”,i);
for(i=1;i<=n;++i)
{
printf(“\n\n%d”,i);
for(j=1;j<=n;++j)
{
if(board[i]==j)
printf(“\tQ”);
else
printf(“\t-“);
}
}
}
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++1)
{
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==ans(i-row))
return 0;
}
return 1;
}
void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
if(place(row,column))
{
board[row]=column;
if(row==n)
print(n);
else
lOMoARc PSD|28104798
lOMoARc PSD|28104798
queen(row+1,n);
}
}
}
void main()
{
int n,i,j;
void queen(int row,int n);
printf(“Enter number of Queens:”);
scanf(“%d”,&n);
if(n<=3)
printf(“Number should be greater than 3”);
else
queen(1,n);
}
lOMoARc PSD|28104798
OUTPUT:
Solution 1:
1 2 3 4
1 - Q - -
2 - - - Q
3 Q - - -
4 - - Q -
Solution 2:
1 2 3 4
1 - - Q -
2 Q - - -
3 - - - Q
4 - Q - -
D:\siya
lOMoARc PSD|28104798
RESULT:
EX.NO: 11
TRAVELLING SALESPERSON PROBLEM
DATE:
AIM:
ALGORITHM:
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++)
{
lOMoARc PSD|28104798
lOMoARc PSD|28104798
scanf(“%d”,&matrix[i][j]);
}
visited_cities[i]=0;
}
printf(“\nEnterted 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;
lOMoARc PSD|28104798
OUTPUT:
cost matrix
1 2 3 4
5 6 78
9 8 4 3
1 2 3 4
5 6 7 8
3 4 5 6
9 8 4 3
Path: 1 4 3 2 1
Minimum Cost: 17
lOMoARc PSD|28104798
RESULT:
EX.NO: 12
IMPLEMENT RANDOMIZED ALGORITHMS FORFINDING
DATE: THE KTH SMALLEST NUMBER
AIM:
To implement randomized algorithms for finding kth smallest number
ALGORITHM:
2. Then partition to the array arount the pivot, its help to all the smaller elementwere 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 than the kth element then repeat the process of the leftsubarray
lOMoARcPSD|28104798
lOMoARcPSD|28104798
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[pivpt])
{
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);
}
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: “);
lOMoARcPSD|28104798
lOMoARcPSD|28104798
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);
}
lOMoARcPSD|28104798
OUTPUT:
The original sequence is: 909 967 552 524 735 383 616 718 904 945 730 173
143 954 482 307 228 35 224 703
RESULT: