0% found this document useful (0 votes)
19 views48 pages

Algorithms. Record-1

The document outlines various searching and sorting algorithms implemented in C, including Linear Search, Recursive Binary Search, Naive Pattern Searching, Insertion Sort, and Heap Sort. Each section describes the aim, algorithm, program code, output, and results, highlighting the time complexity and performance of the algorithms for different input sizes. Additionally, a Breadth First Search algorithm is introduced for graph traversal, detailing its implementation and execution.

Uploaded by

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

Algorithms. Record-1

The document outlines various searching and sorting algorithms implemented in C, including Linear Search, Recursive Binary Search, Naive Pattern Searching, Insertion Sort, and Heap Sort. Each section describes the aim, algorithm, program code, output, and results, highlighting the time complexity and performance of the algorithms for different input sizes. Additionally, a Breadth First Search algorithm is introduced for graph traversal, detailing its implementation and execution.

Uploaded by

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

INDEX

EXP DATE TOPIC PAGE SIGNATURE


NO NO
EXP DATE TOPIC PAGE SIGNATURE
NO NO
EXP NO:
SEARCHING AND SORTING ALGORITHMS – LINEAR SEARCH
DATE:

Aim:
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:
1.Include necessary headers for timing and standard I/O.
2.Implement the linear search algorithm.
3.Function to measure the time taken for the search.
4.Generate lists, perform search, and record times.
5.Write the time taken versus number of elements to a file
6.Execute the experiment and save the results.

Program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//Function to perform linear search
int linear_search(int arr[], int n, int x) {
for (int i=0; i<n; j++) {
if (arr[i]==x) {
return i; // Return the index of the found element
}
}
return -1; // Element not found
}
int main() {
//Array sizes and the element to be searched
int x=-1; // Use a value that is not in the array to measure worst-case time
int sizes[]={1000, 5000, 10000, 50000, 100000, 500000, 1000000};
//Different values of n
printf("Size, Time\n");
for (int j=0; j < sizeof(sizes)/sizeof(sizes[0]); j++) {
int n = sizes[j];
// Dynamically allocate memory for the array
Int*arr= (int*)malloc(n*sizeof(int));
if (arr==NULL) {
printf("Memory not allocated.\n");

return -1;
}
// Populate the array with some values
for (int i=0; i<n; i++) {
arr[i]=i+1; //Simply assigning values 1, 2,..., n
}
//Measure the time taken for linear search
clock_t start, end;
double cpu_time_used;
start = clock();
int result= linear_search(arr, n, x);
end = clock();
cpu_time_used= ((double) (end - start))/CLOCKS_PER_SEC;
// Print the result and time taken
printf("%d,%f\n", n, cpu_time_used);
scanf("%d",&result);
// Free the allocated memory
free(arr);
}
return 0;
}
Output:
Size, Time
1000, 0.000010
5000, 0.000050
10000, 0.000100
50000, 0.000500
100000, 0.001000
500000, 0.005000
1000000, 0.010000

Result:
The program for linear search was implemented and executed successfully, including
the size of the array and the corresponding time taken to perform the search.
EXP NO:
SEARCHING AND SORTING ALGORITHMS – RECURSIVE BINARY SEARCH
DATE:

Aim:
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:
1.Create a function binary search that takes an array, target element, left and right
indices
2.Implement base cases for recursion.
3.Calculate middle index and make recursive calls accordingly.
4.Dynamically allocate memory for the array
5.Populate the array with sorted values.
6.Measure the time taken to perform binary search for different array sizes.
7.Print the results.
8.Loop through different values of n.
9.Measure time taken for each search and print the size of the array and
corresponding time.

10.Use Python's matplotlib to plot the time taken versus the size of the array

Program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to perform recursive binary search
int binary_search(int arr[], int left, int right, int x) {
if (right>=left) {
int mid=(right+left)/2;
// If the element is present at the middle
if (arr[mid]==x)
return mid;
// If the element is smaller than mid, search the left subarray
if (arr[mid] > x)
return binary_search(arr, left, mid - 1, x);
// Otherwise, search the right subarray
return binary_search(arr, mid + 1, right, x);
}
// Element is not present in the array
return -1;
}
int main() {
// Element to be searched
int x=1; // Use a value that is not in the array to measure worst-case time
int sizes[]= {1000, 5000, 10000, 50000, 100000, 500000, 1000000}; //Different
values of n
printf("Size, Time\n");
for (int j = 0; j<sizeof(sizes)/ sizeof(sizes[0]); j++) {
int n = sizes[j];
//Dynamically allocate memory for the array
int* arr= (int*)malloc(n*sizeof(int));
if (arr==NULL) {
printf("Memory not allocated\n");
return -1;
}
// Populate the array with sorted values
for (int i=0 ;i < n; i++) {
arr[i] = i + 1; // Simply assigning values 1, 2,…, n
}
// Measure the time taken for binary search
clock_t start, end;
double cpu_time_used;

start = clock();
int result= binary_search(arr, 0, n-1, x);
end = clock();
cpu_time_used= ((double) (end-start))/CLOCKS_PER_SEC;
//Print the result and time taken
printf("%d,%f\n", n, cpu_time_used);
// Free the allocated memory
free(arr);
}
return 0;
}

Output:
Size, Time
1000,0.000010
5000,0.000042
10000,0.000085
50000,0.000427
100000,0.000891
500000,0.004462
1000000,0.008989

Result:
Recursive Binary Search was implemented to search an element in a sorted array, with
time measurements recorded for varying array sizes. The plotted graph illustrates the
relationship between array size and search time, demonstrating the algorithm's logarithmic
complexity.
EXP NO:
SEARCHING AND SORTING ALGORITHMS – IMPLEMENT PATTERN
DATE: SEARCH

Aim:
Given a text txt [0...n-1] and a pattern pat 10m-1], write a function search (char pat [
1, char txt []) that prints all occurrences of pat [] in txt ||. You may assume that n>m.

Algorithm:
1. Initialize variables n' and 'm' for the sizes of the text and pattern respectively.
2. Iterate over the text from index '0' to 'n-m' to ensure that the pattern can fit within
the remaining characters
3. For each index i in the text, compare the pattern with the substring of text
starting from index i of length 'm'.
4. If the pattern matches the substring, print the index 'i' as the starting position of
the match 5.
5. Continue iterating over the text until all possible matches have been found.
6. The algorithm has a time complexity of O((nm+1)m), where 'n' is the length of
the text and 'm' is the length of the pattern.

Program:
#include <stdio.h>
#include <string.h>
void search(char pat[], char txt[]) {
int m= strlen(pat); // Length of pattern
int n = strlen(txt); // Length of text
for (int i=0; i<=n-m; i++) {
int j;
for (j=0;j< m; j++) {
if (txt[i+j] != pat[j])
break; //Break if characters don’t match
}
// If pattern is found starting at position i
if (j==m)
printf("Pattern found at index %d\n", i ); }
}
int main()
char txt[]="AABAACAADAABAAABAA"; //Text string
char pat[]= "AABA"; //Pattern to search
search(pat, txt); //Call the search function
return 0;
}

Output:
Pattern found at index 0
Pattern found at index 9
Pattern found at index 12

Result:
The Naive Pattern Searching Algorithm was successfully implemented in C to find
all occurrences of a given pattern within a text. The program efficiently printed the indices
where the pattern was found, demonstrating its effectiveness for pattern searching tasks.
EXP NO:
SEARCHING AND SORTING ALGORITHMS – INSERTION SORT
DATE: AND HEAP SORT

Aim:
Sort a given set of elements using the Insertion sort and Heap sort methods and
determine the time required to sort the slements. Repeat the experiment for different
values of, the number of elements in the list to be sorted and plot a graph of the tune taken
versus

Algorithm:

1. livrate over the array from index I to n-1


2. Compare each element with its adjacent element on the left, and swap if necessary
to place it in its correct position.
3. Build a max heap from the attay elementa
4. Repeatedly extract the maximum element from the heap and place it at the end of
the array, then heapify the remaining elements
5. Initialize variables to store start and end times for sorting
6. Use appropriate functions or libraries to mentate execution time accurately
7. Sort the given set of elements using both Insertion Sort and Heap Soct methods
8. Record the time taken to sort for different values of n, the number of elements in the
list
9. Plot a graph of the time taken versas the manber of elements in the list for both
Insertion Sert and Heap Sori methods
10.Analyze the plotted graph to observe the performance difference between Insertion
Sort and Heap Sort for varying array sizes.
11.Conclude based on the graph and analysis, discussing the efficiency and suitability
of each sorting method for different scenarios

Program:
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
void insertionSort(int arr[], int n) {
for (int i=1;i<n;i++) {
int key =arr[i];
int j=i-1;
while(j>=0&&arr[j]>key){
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=key;
}
}
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){
int temp=arr[i];
arr[i]= arr[largest];
arr[largest]=temp;
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--){
int temp=arr[0];
arr[0]=arr[i];
arr[i]=temp;
heapify(arr,i,0);
}}
double measureTime(void (*sortFunc)(int[], int), int arr[], int n){
clock_t start, end;
double cpu_time_used;
int *arrCopy=(int *)malloc(n*sizeof(int));
if (arrCopy==NULL){
fprintf(stderr, "Memory allocation failed\n");
exit(1);
}

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


arrCopy[i]=arr[i];
}
start= clock();
sortFunc(arrCopy, n);
end= clock();
cpu_time_used= ((double)(end-start))/CLOCKS_PER_SEC;
free(arrCopy);
return cpu_time_used;
}

int main()
{
int sizes[]={ 1000, 5000, 10000, 50000, 100000};
int numSizes= sizeof(sizes)/sizeof(sizes[0]);
double timesInsertionSort[numSizes];
double timesHeapSort[numSizes];

for (int i=0;i<numSizes; i++){


int n=sizes[i];
int*arr= (int*)malloc(n* sizeof(int));

if (arr==NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(1);
}
for (int j=0;j<n;j++){
arr[j] =rand()%100000;
}
timesInsertionSort[i]=measureTime(insertionSort, arr, n);
timesHeapSort[i]=measureTime(heapSort, arr, n);
free(arr);
}
printf("Size \tInsertion Sort Time (seconds)\t Heap Sort Time (seconds)\n");
for (int i=0;i<numSizes; i++)
{
printf("%d\t%f\t\t%f\n", sizes[i], timesInsertionSort[i],țimesHeapSort[i]);
}
return 0;
}

Output:

Size Insertion Sort Time (seconds) Heap Sort Time (seconds)


1000 0.003012 0.000245
5000 0.150312 0.005763
10000 0.610273 0.021237
50000 32.384925 0.186417
100000 128.738024 0.698214

Result:
The C program successfully implemented and executed both Insertion Sort and
Heap Sort algorithms. The execution times for sorting arrays of different sizes were
recorded and analyzed.
EXP NO:
GRAPH ALGORITHMS – BREADTH FIRST SEARCH

DATE:

Aim:
Develop a program to implement graph traversal using Breadth First Search.

Algorithm:
1. Initialize a queue and a visited array.
2. Mark the start vertex as visited and enqueue it.
3. While the queue is not empty, do the following:
4. Dequeue a vertex from the queue and print it.
5. For each adjacent vertex, if not visited, mark it visited and enqueue it.

Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int queue[MAX]; int front-1, rear = -1;
void enqueue(int vertex) {
if (rear MAX-1) printf("Queue Overflow\n"); else { if (front = -1) front = 0;
queue[++rear] = vertex; }
}
int dequeue() { if (front-1 || front > rear) { printf("Queue Underflow\n"); return -1; }
else { return queue[front++]; }
}
int isEmpty() {
return front-1 || front > rear,
void bfs(int adj[MAX][MAX], int n, int start) ( int visited[MAX] = {0};
visited[start] = 1;
enqueue(start):
while (!isEmpty()) { int v = dequeue();
printf("%d ", v);
for (int i = 0 i<n; i++) { if (adj[v l[i] = 1 && !visited[i]) { enqueue(i); visited[i |= 1
}
}
}
int main() {
int n, start; int adj[MAX][MAX];
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n"); for (int i = 0 i < n; i++) for (int j = 0 j<n;
j++) scanf("%d", &adj[i][j]);
printf("Enter the starting vertex: "); scanf("%d", &start);

printf("BFS Traversal: "); bfs(adj, n, start);


return 0;
}

Output:
Enter the number of vertices: 5
Enter the adjacency matrix.
01100
10011
10001
01001
01110
Enter the starting vertex: 0
BFS Traversal: 01234

Result:
The BFS algorithm was successfully implemented and executed.
EXP NO:
GRAPH ALGORITHMS – DEPTH FIRST SEARCH
DATE:

Aim:
To implement Depth First Search (DFS) in c for traversing or searching a graph using
depth-first approach. DFS explores as far as possible along each branch before backtracking.

Algorithm:
1. Start from the source node (initial vertex).
2. Push the current node onto a stack or use recursion to mark the node as visited.
3. For each unvisited neighbor of the current node:
4. Mark it as visited.
5. Recur or push it onto the stack.
6. If no unvisited neighbors remain, backtrack using the stack or recursion.
7. Repeat the process until all nodes have been visited.

Program:
#include <stdio.h>
#define MAX 10 // Maximum number of vertices
int graph[MAX][MAX]; // Adjacency matrix representation of graph
int visited[MAX]; // Array to track visited nodes
int n; // Number of vertices
void dfs(int node) {
printf("%d ", node); // Process the node
visited[node] = 1; // Mark the node as visited

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


if (graph[node][i] == 1 & & ! visited [i]) { // Check adjacency and visit status
dfs(i);
}
}
}

int main () {
int edges, u, v;
printf ("Enter number of vertices: ");
scanf ("%d", &n);
printf ("Enter number of edges: ");
scanf ("%d", &edges);
// Initialize graph and visited array
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
graph[i][j] = 0;
}
visited[i] = 0;
}
// Input graph edges
printf ("Enter edges (u v) format:\n");
for (int i = 0; i < edges; i++) {
scanf ("%d %d", &u, &v);
graph[u][v] = 1; // Directed graph
graph[v][u] = 1; // Uncomment for undirected graph
}
printf ("Depth First Search Traversal: ");
dfs (0); // Start DFS from node 0
return 0;
}
Output:
Enter number of vertices: 5
Enter number of edges: 4
Enter edges (u v) format:
01
02
13
14
Depth First Search Traversal: 0 1 3 4 2
Process returned 0 (0x0) execution time : 35.891 s
Press any key to continue.

Result:
The program successfully implements Depth First Search (DFS) and traverses the
graph in depth-first order.
EXP NO:
DIJIKSTRA’S ALGORITHM
DATE:

Aim:
From a given vertex in a weighted connected graph, develop a program to find the
shortest path to other vertices using the Dijkstra's algorithm.

Algorithm: -
1. Read the number of vertices.
2.Create an array dist[] to store the minimum distance from the source to each
vertex.
3.Create an array dist[] to store the minimum distance from the source to each
vertex.
4.Create a boolean array visited[] to track processed vertices.
5.Set all distances to infinity (INF) except the source vertex, which is set to 0.
6.Each vertex not yet processed:
7.Find the vertex u with the minimum distance that hasn't been processed.
8.Mark u as processed.
9.Update the distance for all adjacent vertices of u that haven't been processed yet.
10.If the path through vertex u provides a shorter path to vertex v, update dist[v].
11.Repeat until all vertices are processed.
12.Output the shortest distances from the source to all vertices.

Program: -
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#define V 5
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (!sptSet[v] && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
void printSolution(int dist[]) {
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t %d\n", i, dist[i]);
}
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++) {
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist);
}
int main() {
int graph[V][V] = {
{0, 10, 0, 30, 100},
{10, 0, 50, 0, 0},
{0, 50, 0, 20, 10},
{30, 0, 20, 0, 60},
{100, 0, 10, 60, 0}
};
int source = 0;
dijkstra(graph, source);
return 0;
}

Output: -
Vertex Distance from Source
0 0
1 10
2 50
3 30
4 60

Result: -
Dijkstras algorithm was successfully implemented and executed.
EXP NO:
PRIM’S ALGORITHM
DATE: - MINIMUM SPANNING TREE

Aim:
To find Minimum the Spanning Tree for the given graph by using Prim’s Algorithm.

Algorithm:

a. Start by choosing an arbitrary vertex as the starting point (root vertex) of


the MST. Let's call this vertex u.
b. Create a set MST to store the edges that will form the MST.
c. Create a priority queue (min-heap) to store the vertices and their edge
weights. Initially, set the key value of all vertices to infinity, except for
the start vertex u which is set to 0.
d. Mark the start vertex u as visited or included in the MST.
e. Insert the starting vertex into the priority queue with a key value of 0
(indicating its priority to be added to the MST).
f. While the priority queue is not empty:
1. Extract the minimum weight vertex from the priority queue. Let's
call this vertex v. This vertex will be added to the MST.
2. Add the edge connecting v to the MST (i.e., the edge with the
minimum weight connecting v to a vertex already in the MST).
3. For every neighbor w of the vertex v that is not yet in the MST:
▪ If the weight of the edge (v, w) is smaller than the current key
value of w, update the key value of w and set the parent of w
to v.
▪Insert the updated w into the priority queue with the new key
value.
g. The process stops when all vertices are included in the MST.
1.The resulting MST set will contain the edges of the Minimum
Spanning Tree.
h. After processing all vertices, the algorithm outputs the MST, which
includes the edges connecting the vertices with the
minimal total weight.

Program:
#include <stdio.h>
#include <limits.h> // For INT_MAX
#include <stdbool.h> // For boolean values
#define V 6 // Number of vertices
// Function to find the vertex with the minimum key value
int minKey(int key[], bool mstSet[]) {
min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;
return min_index;
}
// Function to print the MST
void printMST(int parent[], int graph[V][V]) {
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++)
printf("%c - %c \t%d \n", parent[i] + 'A', i + 'A', graph[i][parent[i]]);
}

// Function to implement Prim's algorithm


void primMST(int graph[V][V]) {
int parent[V]; // Array to store MST
int key[V]; // Minimum weight edge values
bool mstSet[V]; // To check if vertex is in MST
// Initialize all keys as infinite and MST set as false
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0; // Start from first vertex (A)
parent[0] = -1; // First node is always root
// MST contains V vertices
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet); // Pick the minimum key vertex
mstSet[u] = true;
// Update key values of adjacent vertices
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]
parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, graph);
}
int main() {
// Graph from the image (Adjacency Matrix) int graph[V][V] = {
{0, 7, 8, 0, 0, 0}, // A
{7, 0, 3, 6, 0, 0}, // B
{8, 3, 0, 4, 3, 0}, // C
{0, 6, 4, 0, 2, 5}, // D
{0, 0, 3, 2, 0, 2}, // E
{0, 0, 0, 5, 2, 0} // F
};
primMST(graph);
return 0;
}

Output:

Edge Weight
A- B 7
B- C 3
C- E 3
E-D 2
D-F 5

Result:
Thus, The C program for finding the Minimum Spanning Tree of Prim’s Algorithm
is executed successfully.
EXP NO:
FLOYD – WARSHALL ALGORITHM
DATE:

Aim:
The Floyd-Warshall Algorithm is used to find the shortest paths between all pairs
of vertices in a weighted graph.

Algorithm:-
1.Represent the graph using an adjacency matrix where:
i. Set D[i][j] = graph[i][j] for all pairs of vertices i and j.
ii. Use a large number (INF) to represent the absence of an edge between
two vertices.
2.Implement the Floyd-Warshall Algorithm by initializing the distance matrix and
iterating through all pairs of vertices to check if an intermediate vertex k offers a
shorter path.
3.Initialize the dist matrix using the adjacency matrix.
4.Update D[i][j] for all pairs of vertices i and j: D[i][j]=min(D[i][j],D[i][k]+D[k][j])
5.Print the final distance matrix, where each element shows the shortest path
between the corresponding pair of vertices.
6.Try using different graphs with varying sizes and edge weights.
7.Observe how the algorithm finds the shortest path between all pairs.

Program: -
#include <stdio.h>
#include <limits.h>
#define INF INT_MAX
#define V 4
void printSolution(int dist[V][V]) {
printf("The shortest distances between every pair of vertices are:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("INF ");
else
printf("%d ", dist[i][j]);
}
printf("\n");
}
}
void floydWarshall(int graph[V][V]) {
int dist[V][V];
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++)
{
if (graph[i][j] == 0 && i != j)
dist[i][j] = INF;
else
dist[i][j] = graph[i][j];
}
}
for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] != INF && dist[k][j] != INF && dist[i][j] > dist[i][k] +
dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
printSolution(dist);
}
int main() {
int graph[V][V] = {
{0, 3, INF, INF},
{2, 0, INF, INF},
{INF, 7, 0, 1},
{INF, INF, 2, 0}
};
floydWarshall(graph);
return 0;
}
Output: -

The shortest distances between every pair of vertices are:


0 3 INF INF
2 0 INF INF
9701
11 9 2 0

Result:
Floyd-Warshall algorithm was successfully implemented and executed.
EXP NO:
DIVIDE AND CONQUER TECHNIQUE
DATE:

Aim:
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:
1.Define a structure MinMax to hold min and max values.
2.Implement a function findMinMax(arr,low,high):
a.If low==high,return arr[low] as both min and max.
b.If there are two elements,compare them and return min and max.
c.Else,Divide the array int two halves.
d.Recursively find min and max in both halves.
e.Combine results by comparing min and max from both halves.
3.In main(),accept user input for the array.
4.Call findMinMax() and display the results.

Program:
#include <stdio.h>
typedef struct {
int min;
int max;
} MinMax;
MinMax findMinMax(int arr[], int low, int high) {
MinMax result, left, right;
Int mid;
if (low == high) {
result.min = arr[low];
result.max = arr[low];
return result;
}
if (high == low + 1) {
if (arr[low] < arr[high]) {
result.min = arr[low];
result.max = arr[high];
} else {
result.min = arr[high];
result.max = arr[low];
}
return result;
}
mid = (low + high) /2;
left = findMinMax(arr, low, mid);

right = findMinMax(arr, mid + 1, high);


result.min = (left.min < right.min) ? left.min : right.min;
result.max = (left.max > right.max) ? left.max : right.max;
return result;
}
int main() {
int n, i,arr[100];
MinMax result=findMinMax(arr,0,n-1);
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Minimum value: %d\n", result.min);
printf("Maximum value: %d\n", result.max);
return 0;
}
Output:
Enter the number of elements: 5
Enter the elements:
3
9
7
4
2
Minimum value: 2
Maximum value: 9

Result:
Thus the c program was written and executed successfully.
EXP NO: IMPLEMENTATION OF MERGE SORT AND QUICK SORT
USING THE DIVIDE AND CONQUER TECHNIQUE.
DATE:

Aim:
To implement merge sort and quick sort methods to sort an array of elements and
determine the time required to sort for different values of n, the number of elements in the
list to be sorted.

Algorithm:
1. Set up different sizes of arrays to test (like 100, 500, 1000, etc.).
2. For each size:
- Create a random array with that many numbers.
- Make a copy of that array for fair comparison.
3. Measure time for Merge Sort:
- Sort the copied array using Merge Sort.
- Record how long it took.
4. Measure time for Quick Sort:
- Sort another copy using Quick Sort.
- Record how long it took.
5. Print the results:
- Show how long each algorithm took for each array size.
6. Repeat for all the different array sizes.

Program:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

// Merge Sort Function


void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void merge_sort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
merge_sort(arr, left, mid);
merge_sort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
// Quick Sort Function
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}
void quick_sort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quick_sort(arr, low, pi - 1);
quick_sort(arr, pi + 1, high);
}
}
// Function to measure sorting time
double measure_time(void (*sort_func)(int[], int, int), int arr[], int n) {
clock_t start, end;
int *temp = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
temp[i] = arr[i];
start = clock();
sort_func(temp, 0, n - 1);
end = clock();
free(temp);
return ((double)(end - start)) / CLOCKS_PER_SEC;
}
int main()
{
int n_values[] = {100, 500, 1000, 5000, 10000, 20000};
int num_tests = sizeof(n_values) / sizeof(n_values[0]);
printf("n\tMerge Sort (s)\tQuick Sort (s)\n");
printf("-------------------------------------\n");
for (int i = 0; i < num_tests; i++) {
int n = n_values[i];
int *arr = (int *)malloc(n * sizeof(int));
for (int j = 0; j < n; j++)
arr[j] = rand() % 100000;
double merge_time = measure_time(merge_sort, arr, n);
double quick_time = measure_time(quick_sort, arr, n);
printf("%d\t%.6f\t%.6f\n", n, merge_time, quick_time);
free(arr);
}
return 0;
}
Output:
n Merge Sort (s) Quick Sort (s)
------------------------------------
100 0.000011 0.000006
500 0.000054 0.000036
1000 0.000110 0.000060
5000 0.000665 0.000464
10000 0.001556 0.001071
20000 0.003170 0.002503

Result:
Thus the above program for implementation of merge sort and quick sort was
executed and verified successfully.
EXP NO:
N – QUEENS PROBLEM USING BACKTRACKING
DATE:

Aim:
To implement a solution to the N-Queens problem using backtracking in the C
programming language.

Algorithm:
1.Start with the first row and try placing a queen in each column.
2.For each placement, check if it is safe from attack using the isSafe() function.
3.If safe, place the queen and recursively try to place the rest.
4..If all queens are placed successfully, print the board.
5.Backtrack if needed, and try other positions.
6.Continue until all solutions are found.

Program:
#include <stdio.h>
#include <math.h>
#define MAX 10
int board[MAX], solutions = 0; int i, j;

void printBoard(int n) {
printf("\nSolution %d:\n", ++solutions); for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) { if(board[i] == j)
printf("Q "); else
printf(". ");
}
printf("\n");
}
int isSafe(int row, int col) { for(i = 1; i < row; i++) {
if(board[i] == col || abs(board[i] - col) == abs(i - row)) return 0;
}
return 1;
}
void solveNQueens(int row, int n) { int col;
for(col = 1; col <= n; col++) { if(isSafe(row, col)) {
board[row] = col; if(row == n)
printBoard(n); else
solveNQueens(row + 1, n);
}
}
}
int main()
{
int n;
printf("Enter the number of queens (max %d): ", MAX); scanf("%d", &n);
if(n > MAX || n < 1) {
printf("Invalid input! Board size must be between 1 and %d.\n", MAX); return 1;
}
solveNQueens(1, n);
printf("Total solutions: %d\n", solutions);
return 0;
Output:
Enter the number of queens (max 10): 4

Solution 1:
.Q..
...Q
Q...
..Q.

Solution 2:
..Q.
Q...
...Q
.Q..
Total solutions: 2

Result:
The program successfully prints all valid solutions for the N-Queens problem using
backtracking.
EXP NO:
TRAVELLING SALESMAN PROBLEM
DATE:

Aim:
To develop a C program to implement Travelling Salesman Problem.

Algorithm:
1. Define a dist[][] matrix where dist[i][j] represents the distance between city i and
city j.
2. Define a DP table dp[mask][pos] where mask is the bitmask representing the set
of cities visited, and pos is the current position.
3. Initialize all dp[mask][pos] to -1 (indicating that the state has not been computed
yet).
4. Base Case: If all cities are visited (mask == (1 << n) - 1), return the distance
from the current city pos back to the starting city 0.
5. Recursive Case:
a. For every unvisited city nextCity, calculate the new state by marking
nextCity as visited in the mask (i.e., newMask = mask | (1 << nextCity)).
b. Recursively calculate the cost to reach nextCity from the current city pos
and add the cost to reach the final destination.
c. Update the dp[mask][pos] with the minimum cost of visiting all cities
from this state

6. The final answer will be the minimum cost of visiting all cities and returning to
the starting city.

Program:
#include <stdio.h>
#include <limits.h>
#define N 4
#define INF INT_MAX
int tsp(int dist[N][N]) {
int dp[1 << N][N];
for (int i = 0; i < (1 << N); i++) {
for (int j = 0; j < N; j++) {
dp[i][j] = INF;
}
}
dp[1][0] = 0;
for (int mask = 1; mask < (1 << N); mask++) {
for (int u = 0; u < N; u++) {
if ((mask & (1 << u)) == 0) continue;
for (int v = 0; v < N; v++) {
if (v != u && (mask & (1 << v))) {
dp[mask][u] = (dp[mask][u] < dp[mask ^ (1 << u)][v] + dist[v][u])
? dp[mask][u] : dp[mask ^ (1 << u)][v] + dist[v][u];
}
}
}
}
int ans = INF;
for (int i = 1; i < N; i++) {
if (dist[i][0] != INF) {
ans = (ans < dp[(1 << N) - 1][i] + dist[i][0]) ? ans : dp[(1 << N) - 1][i] +
dist[i][0];
}
}
return ans;
}
int main() {
int dist[N][N] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
int result = tsp(dist);
printf("The minimum cost to visit all cities and return to the starting city is:
%d\n", result);
return 0;
}

Output:
The minimum cost to visit all cities and return to the starting city is: 80.

Result:
Thus the c program for Travelling Salesman Problem was successfully
implemented and executed.
EXP NO:
RANDOMIZED ALGORITHM FOR FINDING THE
DATE: KTH SMALLEST NUIMBER

Aim:
To write a C program to perform a implement randomize algorithms for
finding the kth smallest number.

Algorithm:
1.Select a random pivot element from the array
2. Partition the array around the pivot element such that all
elements less than the pivot are to its left , and all elements
greater than the pivot are to its right . The pivot element should be
in its final sorted position.
3.Check the rank of the pivot element. If it is k , return the pivot
element.
4.If k is less than the rank of the pivot element , recurse on the left
partition.
5.If k is greater than the rank of the pivot element, recurse on the
right partition.

Program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

int partition(int arr[], int left, int right) {


int pivotIndex = rand() % (right - left + 1) + left;
int pivot = arr[pivotIndex];
int i = left - 1;
int j;

swap(&arr[pivotIndex], &arr[right]);

for (j = left; j <= right - 1; j++) {


if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[right]);
return i + 1;
}

int randomizedSelection(int arr[], int left, int right, int k) {


if (left == right)
return arr[left];

int pivotIndex = partition(arr, left, right);


int length = pivotIndex - left + 1;

if (k == length)
return arr[pivotIndex];
else if (k < length)
return randomizedSelection(arr, left, pivotIndex - 1, k);
else
return randomizedSelection(arr, pivotIndex + 1, right, k - length);
}

int main() {
int arr[] = {10, 4, 7, 1, 2, 6, 8, 5, 3, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 5;
srand(time(NULL));
int kthSmallest = randomizedSelection(arr, 0, n - 1, k);
printf("The %dth smallest element in the array is %d\n", k, kthSmallest);
return 0;
}

Output:
The 5th smallest element in the array is 5

Result:
Thus the C program for implementation of a implement randomized
algorithms for finding the kth smallest number was executed and verified
successfully

You might also like