0% found this document useful (0 votes)
3 views58 pages

Algorithms Lab

The document outlines the regulations for the Algorithms Laboratory course at Karpaga Vinayaga College of Engineering and Technology, detailing various experiments including Linear Search, Recursive Binary Search, Pattern Matching, Insertion Sort, and Heap Sort. Each experiment includes objectives, algorithms, C program implementations, and results demonstrating successful execution. The document emphasizes measuring time taken for each algorithm and plotting results against varying input sizes.

Uploaded by

chitra
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)
3 views58 pages

Algorithms Lab

The document outlines the regulations for the Algorithms Laboratory course at Karpaga Vinayaga College of Engineering and Technology, detailing various experiments including Linear Search, Recursive Binary Search, Pattern Matching, Insertion Sort, and Heap Sort. Each experiment includes objectives, algorithms, C program implementations, and results demonstrating successful execution. The document emphasizes measuring time taken for each algorithm and plotting results against varying input sizes.

Uploaded by

chitra
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/ 58

KARPAGA VINAYAGA

COLLEGE OF ENGINEERING AND TECHNOLOGY

DEPARMENT OF COMPUTER SCIENCE AND ENGINEERING


REGULATIONS 2021

CS3401 ALGORITHMS LABORATORY

Name:

Reg.No:

Department:

Year/Sem:
INDEX

S.NO DATE NAME OF THE EXPERIMENT PAGE MARK SIGNATURE


NO
EXP.NO:1 IMPLEMENTATION OF 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. Declare an array.
2. The linear_search function takes an array arr and an element x as input, and searches
for the element in the array using linear search.
3. If the element is found, it returns the index of the element in the array. Otherwise, it
returns -1.
4. The program defines a list n_values containing different values of n to test the linear
search algorithm on.
5. It then loops through this list, generates a random listof n elements, and searches for a
random element in the list.
6. It measures the time taken to perform the search using the time module, and appends the
time taken to a list time_values.
7. Finally, the program uses matplotlib library to plot a graph of the time takenversus n.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Function to perform linear search


int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index of the target if found
}
}
return -1; // Return -1 if the target is not found
}

int main() {
int size;
int target;

// Prompt user for the size of the array


printf("Enter the number of elements in the array: ");
scanf("%d", &size);

// Dynamically allocate memory for the array


int* arr = (int*)malloc(size * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

// Prompt user to enter array elements


printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

// Prompt user for the target value


printf("Enter the target value to search for: ");
scanf("%d", &target);

// Record the start time


clock_t start = clock();

int result = linearSearch(arr, size, target);

// Record the end time


clock_t end = clock();

double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;


if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found\n");
}
printf("Time taken: %f seconds\n", time_taken);
free(arr);
return 0;
}

OUTPUT:

Enter the number of elements in the array: 5


Enter 5 elements:
4
2
7
1
9
Enter the target value to search for: 7
Element found at index 2
Time taken: 0.000000 seconds

RESULT:
Thus the C program for implementation of linear search program was executed and verified
successfully.
EXP.NO:2 IMPLEMENTATION OF RECURSIVE BINARY SEARCH
DATE :
AIM :
To Implement recursive Binary Search. Determine the time required to searchan 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. Declare the array.


2. ‘binary_search_recursive’ is a recursive function that takes an array ‘arr’, the lower and
upper bounds of the subarray being searched ‘low ‘and ‘high', and the element being
searched for ‘x’.
3. It returns the index of the elementif it is found, or -1 if it is not found.
4. The function ‘test_binary_search_recursive’ generates arrays of different sizes and runs a
binary search for a random element in each array.
5. It records the timetaken to run the search and plots it on a graph.
6. The graph shows the time taken to search for an element versus the size of the array being
searched.
7. As the size of the array increases, the time taken to searchfor an element increases as well,
but the increase is logarithmic since binary search has a time complexity of O(log n).
PROGRAM :

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

// Recursive binary search function


int binarySearch(int arr[], int left, int right, int target) {
if (left <= right) {
int mid = left + (right - left) / 2;

// Check if target is present at mid


if (arr[mid] == target) {
return mid;
}
// If target is smaller, search the left subarray
if (arr[mid] > target) {
return binarySearch(arr, left, mid - 1, target);
}
// If target is larger, search the right subarray
return binarySearch(arr, mid + 1, right, target);
}
// Target is not present in the array
return -1;
}

// Function to sort the array (using Bubble Sort for simplicity)


void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
int size;
int target;

// Prompt user for the size of the array


printf("Enter the number of elements in the array: ");
scanf("%d", &size);

// Dynamically allocate memory for the array


int* arr = (int*)malloc(size * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

// Prompt user to enter array elements


printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

// Sort the array


bubbleSort(arr, size);

// Prompt user for the target value


printf("Enter the target value to search for: ");
scanf("%d", &target);

// Record the start time


clock_t start = clock();

int result = binarySearch(arr, 0, size - 1, target);


// Record the end time
clock_t end = clock();

double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;

if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found\n");
}

printf("Time taken: %f seconds\n", time_taken);

// Free the allocated memory


free(arr);

return 0;
}

OUTPUT:

Enter the number of elements in the array: 6


Enter 6 elements:
34
7
23
5
89
1
Enter the target value to search for: 23
Element found at index 3
Time taken: 0.000000 seconds

RESULT:
Thus the C program for implementation of recursive binary search was executed andverified
successfully.
EXP.NO: 3 PATTERN MATCHING
DATE :

AIM :

To implement all occurrences of pat [ ] in txt [ ]. You may assume that n > m. Given a text
txt [0...n-1] and a pattern pat [0...m-1], write a function search (charpat [ ], char txt [ ])

ALGORITHM :

1. One way to implement the search function is to use the brute-force approach, which involves
comparing each possible substring of the text with the pattern.

2. The algorithm iterates through the text from the first character to the (n-m)thcharacter and
checks whether the pattern matches the substring of the text starting at that position.

3. If a match is found, the function prints the index of the match.

PROGRAM:

#include <stdio.h>
#include <string.h>
#include <time.h>

// Function to perform naive string matching


void naiveStringMatching(char* pattern, char* text) {
int M = strlen(pattern);
int N = strlen(text);

// Slide pattern over text one by one


for (int i = 0; i <= N - M; i++) {
int j;

// Check for pattern match at current position


for (j = 0; j < M; j++) {
if (text[i + j] != pattern[j]) {
break;
}
}

// If pattern matches
if (j == M) {
printf("Pattern found at index %d\n", i);
}
}
}
int main() {
char text[] = "ABABDABACDABABCABAB";
char pattern[] = "ABABCABAB";

printf("Text: %s\n", text);


printf("Pattern: %s\n", pattern);

// Measure the running time


clock_t start, end;
double cpu_time_used;

start = clock();
naiveStringMatching(pattern, text);
end = clock();

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

printf("Running time: %f seconds\n", cpu_time_used);

return 0;
}

OUTPUT:

Text: ABABDABACDABABCABAB
Pattern: ABABCABAB
Pattern found at index 10
Running time: 0.000001 seconds

RESULT:
Thus the C program implementation of pattern matching was executed and verified successfully.
EXP.NO: 4 IMPLEMENTATION OF INSERTION SORT AND HEAP SORT
DATE :

AIM :

To Sort a given set of elements using the Insertion sort and Heap sort methods and
determine the time required to sort the elements. Repeat the experiment fordifferent values of n, the
number of elements in the list to be sorted and plot a graph of the time taken versus n.

ALGORITHM:

Algorithm for insertion sort:

1. The insertionSort function takes a list of elements and sorts them using the Insertion sort
algorithm.

2.The generateList function generates a list of n random numbers between 1 and 1000.

3.The measureTime function generates a list of n random numbers, sorts it using the insertionSort
function, and measures the time required to sort the list.

4.The plotGraph function generates a list of n values and calls the measureTime function for each
n value. It then plots a graph of the time required to sort the list versus the value of n .

Algorithm for heap sort:

1. The heapify function takes an array arr, the size of the heap n , and the root index i of the
subtree to heapify. It compares the root node with its left and right children and swaps the root with
the larger child if necessary. The function then recursively calls itself on the subtree with the new
root index.

2. The heapSort function takes an array arr and sorts it using the Heap sort algorithm. It first
builds a max heap by heapifying all subtrees bottom-up. It then repeatedly extracts the maximum
element from the heap and places it at the end of the array.

3. The generateList function generates a list of n random numbers between 1 and 1000.

4. The measureTime function generates a list of n random numbers, sorts it using the heapSort
function, and measures the time required to sort the list.

5. The plotGraph function generates a list of n values and calls the measureTime function for
each n value. It then plots a graph of the time required to sort the list versus the value of n .
PROGRAM:INSERTION SORT

#include <stdio.h>
#include <time.h>
// Function to perform insertion sort
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their
current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// Function to print an array


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

int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: \n");


printArray(arr, n);

// Measure the running time


clock_t start, end;
double cpu_time_used;
start = clock();
insertionSort(arr, n);
end = clock();

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

printf("Sorted array: \n");


printArray(arr, n);
printf("Running time: %f seconds\n", cpu_time_used);

return 0;
}

OUTPUT:

Original array:
12 11 13 5 6
Sorted array:
5 6 11 12 13
Running time: 0.000002 seconds
PROGRAM: HEAPSORT

#include <stdio.h>
#include <time.h>
// Function to heapify a subtree rooted at index i
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left = 2*i + 1
int right = 2 * i + 2; // right = 2*i + 2

// See if left child of root exists and is greater than root


if (left < n && arr[left] > arr[largest]) {
largest = left;
}

// See if right child of root exists and is greater than root


if (right < n && arr[right] > arr[largest]) {
largest = right;
}

// Change root if needed


if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;

// Recursively heapify the affected subtree


heapify(arr, n, largest);
}
}

// Main function to perform heap sort


void heapSort(int arr[], int n) {
// Build a max heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
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[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: \n");


printArray(arr, n);

// Measure the running time


clock_t start, end;
double cpu_time_used;

start = clock();
heapSort(arr, n);
end = clock();

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

printf("Sorted array: \n");


printArray(arr, n);
printf("Running time: %f seconds\n", cpu_time_used);

return 0;
}

OUTPUT:
Original array:
12 11 13 5 6
Sorted array:
5 6 11 12 13
Running time: 0.000002 seconds

RESULT:
Thus the C program for implementation of insertion sort and heap sort was executed and verified
successfully.
EXP.NO: 5 IMPLEMENTATION OF GRAPH TRAVERSAL USING BREADTH FIRST SEARCH

DATE :

AIM :

To develop a program to implement graph traversal using Breadth First Search.

ALGORITHM:

Step 1:Start by putting any one of the graph's vertices at the back of a queue.

Step 2:Take the front item of the queue and add it to the visited list.

Step 3:Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to
the back of the queue.

Step 4:Keep repeating steps 2 and 3 until the queue is empty.

PROGRAM:

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

#define SIZE 40

struct queue {
int items[SIZE];
int front;
int rear;
};

struct node {
int vertex;
struct node* next;
};

struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};
// Function prototypes
struct queue* createQueue();
void enqueue(struct queue* q, int value);
int dequeue(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);
struct node* createNode(int v);
struct Graph* createGraph(int vertices);
void addEdge(struct Graph* graph, int src, int dest);
void bfs(struct Graph* graph, int startVertex);

// Function to create a new node


struct node* createNode(int v) {
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

// Function to create a graph with a given number of vertices


struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->numVertices = vertices;

graph->adjLists = (struct node**)malloc(vertices * sizeof(struct node*));


graph->visited = (int*)malloc(vertices * sizeof(int));

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


graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}

return graph;
}

// Function to add an edge between two vertices


void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Uncomment the following lines for undirected graph (if needed)


/*
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
*/
}
// Function to create a queue
struct queue* createQueue() {
struct queue* q = (struct queue*)malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}

// Function to check if the queue is empty


int isEmpty(struct queue* q) {
return q->rear == -1;
}

// Function to enqueue an element into the queue


void enqueue(struct queue* q, int value) {
if (q->rear == SIZE - 1) {
printf("\nQueue is Full!!");
} else {
if (q->front == -1) {
q->front = 0;
}
q->rear++;
q->items[q->rear] = value;
}
}

// Function to dequeue an element from the queue


int dequeue(struct queue* q) {
int item;
if (isEmpty(q)) {
printf("Queue is empty");
item = -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
printf("Resetting queue ");
q->front = q->rear = -1;
}
}
return item;
}

// Function to print the queue


void printQueue(struct queue* q) {
int i = q->front;
if (isEmpty(q)) {
printf("Queue is empty");
}
else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}

// Function to perform Breadth-First Search (BFS) traversal


void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();

graph->visited[startVertex] = 1;
enqueue(q, startVertex);

while (!isEmpty(q)) {
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);

struct node* temp = graph->adjLists[currentVertex];


while (temp) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}

// Main function
int main() {
struct Graph* graph = createGraph(6);

// Example graph (undirected)


addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);

printf("Breadth-First Search (BFS) starting from vertex 0:\n");


bfs(graph, 0);

return 0;
}
OUTPUT:

Queue contains
0 Resetting queue Visited 0

Queue contains 2 1
Visited 2

Queue contains 1 4
Visited 1

Queue contains 4 3
Visited 4

Queue contains
3 Resetting queue Visited 3

=== Code Execution Successful ===

RESULT:

Thus the C program for implementation of graph traversal using breadth first searchwas executed and
verified successfully.
EXP.NO: 6 IMPLEMENTATION OF GRAPH TRAVERSAL USING DEPTH FIRST SEARCH

DATE :

AIM :

To develop a program to implement graph traversal using Depth First Search.

ALGORITHM :
Step 1: Start by putting any one of the graph's vertices on top of a stack.

Step 2:Take the top item of the stack and add it to the visited list.

Step 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.

Step 4:Keep repeating steps 2 and 3 until the stack is empty.

PROGRAM :

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

struct node {
int vertex;
struct node* next;
};

struct Graph {
int numVertices;
int* visited;
struct node** adjLists;
};

// Function prototypes
struct node* createNode(int v);
struct Graph* createGraph(int vertices);
void addEdge(struct Graph* graph, int src, int dest);
void DFS(struct Graph* graph, int vertex);
void printGraph(struct Graph* graph);

// DFS algorithm
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;

graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);
while (temp != NULL) {
int connectedVertex = temp->vertex;
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}

// Create a node
struct node* createNode(int v) {
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

// Create graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->numVertices = vertices;

graph->adjLists = (struct node**)malloc(vertices * sizeof(struct node*));


graph->visited = (int*)malloc(vertices * sizeof(int));

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


graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}

return graph;
}

// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Uncomment the following lines for undirected graph (if needed)


/*
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
*/
}

// Print the graph


void printGraph(struct Graph* graph) {
for (int v = 0; v < graph->numVertices; v++) {
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}

int main() {
struct Graph* graph = createGraph(4);

// Example graph (undirected)


addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);

printf("Graph representation:\n");
printGraph(graph);

printf("\nDFS traversal starting from vertex 2:\n");


DFS(graph, 2);

return 0;
}

OUTPUT:

Adjacency list of vertex 0: 2 -> 1 ->0


Adjacency list of vertex 1: 2 -> 0 ->1
Adjacency list of vertex 2: 3 -> 1 -> 0
Adjacency list of vertex 3: 2 ->

DFS traversal starting from vertex 2:


Visited 2
Visited 3
Visited 1
Visited 0

RESULT:
Thus the C program for implementation of graph traversal using breadth first searchwas executed and
verified successfully.
EXP.NO: 7 IMPLEMENTATION OF DIJIKSTRA’S ALGORITHM
DATE :

AIM: To develop a program to find the shortest paths to other vertices using Dijkstra’s algorithm.

ALGORITHM :
1. First, we define a function ‘dijkstra’ that takes three arguments: the graph represented as an
adjacency matrix, the starting vertex src, and the number of vertices in the graph n.

2. The function returns a list of shortest distances from the source vertex to all other vertices in the
graph.

PROGRAM:

#include <stdio.h>

#define INFINITY 9999


#define MAX 10

void Dijkstra(int Graph[MAX][MAX], int n, int start);

void Dijkstra(int Graph[MAX][MAX], int n, int start) {


int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX], count, mindistance, nextnode, i, j;

// Creating cost matrix from Graph


for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (Graph[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = Graph[i][j];
}
}

// Initializing distance[], pred[] and visited[]


for (i = 0; i < n; i++) {
distance[i] = cost[start][i];
pred[i] = start;
visited[i] = 0;
}

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

while (count < n - 1) {


mindistance = INFINITY;
// Finding the minimum distance vertex from the set of vertices not yet visited
for (i = 0; i < n; i++) {
if (distance[i] < mindistance && !visited[i]) {
mindistance = distance[i];
nextnode = i;
}
}

// Mark the selected vertex as visited


visited[nextnode] = 1;

// Update distance[] and pred[] arrays


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

// Print the distance from the source vertex to each vertex


for (i = 0; i < n; i++) {
if (i != start) {
printf("Distance from vertex %d to %d: %d\n", start, i, distance[i]);
}
}
}

int main() {
int Graph[MAX][MAX] = {
{0, 0, 1, 2, 0, 0, 0},
{0, 0, 2, 0, 0, 3, 0},
{1, 2, 0, 1, 3, 0, 0},
{2, 0, 1, 0, 0, 0, 1},
{0, 0, 3, 0, 0, 2, 0},
{0, 3, 0, 0, 2, 0, 1},
{0, 0, 0, 1, 0, 1, 0}
};
int n = 7; // Number of vertices
int u = 0; // Starting vertex

Dijkstra(Graph, n, u);

return 0;
}
OUTPUT:

Distance from vertex 0 to 1: 3


Distance from vertex 0 to 2: 1
Distance from vertex 0 to 3: 2
Distance from vertex 0 to 4: 4
Distance from vertex 0 to 5: 6
Distance from vertex 0 to 6: 3

RESULT:
Thus the C program to find the shortest paths to other vertices using Dijkstra’salgorithm was
executed and verified successfully.
EX.NO:8 IMPLEMENTATION OF PRIM’S ALGORITHM
DATE :

AIM:
To Find the minimum cost spanning tree of a given undirected graph using Prim’s algorithm.

ALGORITHM :

Step 1: Determine the arbitrary starting vertex.

Step 2: Keep repeating steps 3 and 4 until the fringe vertices (vertices not included in MST) remain.

Step 3: Select an edge connecting the tree vertex and fringe vertex having the minimum weight.

Step 4: Add the chosen edge to MST if it doesn’t form any closed cycle.

Step 5: Exit

PROGRAM :

#include <stdio.h>
#include <limits.h>
#include <stdbool.h>

#define V 5 // Number of vertices in the graph

int minKey(int key[], bool mstSet[]);


void printMST(int parent[], int graph[V][V]);
void primMST(int graph[V][V]);

int minKey(int key[], bool mstSet[]) {


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

void printMST(int parent[], int graph[V][V]) {


printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
}
void primMST(int graph[V][V]) {
int parent[V];
int key[V];
bool mstSet[V];

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


key[i] = INT_MAX;
mstSet[i] = false;
}

key[0] = 0;
parent[0] = -1;

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


int u = minKey(key, mstSet);
mstSet[u] = true;

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

return 0;
}
OUTPUT:
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5

RESULT:
Thus the C program for implementation of minimum cost spanning tree of a givenundirected graph using
Prim’s algorithm.
EX.NO:9 IMPLEMENTATION OF FLOYD’S ALGORITHM FOR THE ALL-PAIRS-
SHORTEST- PATHS PROBLEM
DATE :

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

ALGORITHM:

Step1: In this program, INF represents infinity, and the floyd_algorithm function takes in a
weighted graph represented as a two-dimensional list where graph[i][j] is the weight of the edge
from vertex i to vertex j.

Step:2 The function returns a two-dimensional list dist where dist[i][j] is the shortest path from
vertex i to vertex j.

Step:3 The algorithm first initializes the dist list with the weights of the edges in the graph. It then
uses three nested loops to find the shortest path from vertex i to vertex j through vertex k.

Step:4 If the path through k is shorter than the current shortest path from i to j, it updates dist[i][j]
with the new shortest path.

Step:5 Finally, the program calls the floyd_algorithm function on a sample input graph and prints
the resulting dist list.

PROGRAM:

#include <stdio.h>

#define V 4
#define INF 99999

void printSolution(int dist[][V]);

void floydWarshall(int graph[][V]) {


int dist[V][V];

// Initialize the distance matrix same as input graph matrix


for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
dist[i][j] = graph[i][j];
// Floyd Warshall algorithm
for (int k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
// Pick all vertices as destination for the above picked source
for (int j = 0; j < V; j++) {
// If vertex k is on the shortest path from i to j, then update the value of dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}

// Print the shortest distance matrix


printSolution(dist);
}

void printSolution(int dist[][V]) {


printf("The following matrix shows the shortest distances between every pair of vertices:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}

int main() {
int graph[V][V] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
floydWarshall(graph);

return 0;
}

OUTPUT:

The following matrix shows the shortest distances between every pair of vertices:
0 5 INF 10
INF 0 3 INF
INF INF 0 1
INF INF INF 0

RESULT:

Thus the C program for implementation of Floyd’s algorithm for the All-Pairs- Shortest- Paths problem was
executed and verified successfully.
EX.NO:10 COMPUTE THE TRANSITIVE CLOSURE OF A DIRECTED GRAPH USING
WARSHALL'S ALGORITHM
DATE :

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

ALGORITHM:

Step1: In this program, graph is a two-dimensional list representing the directed graph where
graph[i][j] is 1 if there is an edge from vertex i to vertex j, and 0 otherwise.

Step2: The warshall_algorithm function returns a two-dimensional list representing the transitive
closure of the input graph.

Step3: The algorithm first creates a copy of the input graph as the initial transitive closure. It then
uses three nested loops to update the transitive closure by checking if there is a path from vertex i to
vertex j through vertex k. If there is, it sets transitive_closure[i][j] to 1.

Step4: Finally, the program calls the warshall_algorithm function on a sample input graph and
prints the resulting transitive closure.

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:

Enter the number of vertices: 5


Enter the number of edges: 11
Enter the end vertices of edge 1: 1 1
Enter the end vertices of edge 2: 1 4
Enter the end vertices of edge 3: 3 2
Enter the end vertices of edge 4: 3 3
Enter the end vertices of edge 5: 3 4
Enter the end vertices of edge 6: 4 2
Enter the end vertices of edge 7: 4 4
Enter the end vertices of edge 8: 5 2
Enter the end vertices of edge 9: 5 3
Enter the end vertices of edge 10: 5 4
Enter the end vertices of edge 11: 5 5

Matrix of input data:


1 0 0 1 0
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 1 1 1

Transitive closure:
1 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 1 1 1

RESULT:

Thus the C program to Compute the transitive closure of a given directed graph usingWarshall's algorithm was
executed and verified successfully.
EX.NO:11 IMPLEMENTATION OF FINDING THE MAXIMUM AND MINIMUM
NUMBERS IN A IST USING DIVIDE AND CONQUER TECHNIQUE
DATE :

AIM: To Develop a program to find out the maximum and minimum numbers in a given list of
n numbersusing the divide and conquer technique.

ALGORITHM:

Step1: The find_max_min function recursively divides the list into two halves until the
base cases are reached (when the list contains only one or two elements).

Step2: In the base case, the maximum and minimum numbers are returned.

Step3: In the recursive case, the maximum and minimum numbers of the left and right
halves are computed and the maximum and minimum of the whole list is returned using the
max and min functions.

PROGRAM:

#include <stdio.h>
#include <limits.h>
#include <time.h>

// Function to find the maximum and minimum numbers using divide and conquer
void findMinAndMax(int arr[], int low, int high, int *min, int *max) {
// If there is only one element
if (low == high) {
*min = arr[low];
*max = arr[low];
}
else if (high == low + 1) {
if (arr[low] > arr[high]) {
*max = arr[low];
*min = arr[high];
} else {
*max = arr[high];
*min = arr[low];
}
}
// If there are more than two elements
else {
int mid = (low + high) / 2;
int min1, max1, min2, max2;

// Recursively find the minimum and maximum in the left half


findMinAndMax(arr, low, mid, &min1, &max1);

// Recursively find the minimum and maximum in the right half


findMinAndMax(arr, mid + 1, high, &min2, &max2);

// Find the overall minimum and maximum


*min = (min1 < min2) ? min1 : min2;
*max = (max1 > max2) ? max1 : max2;
}
}

int main() {
int arr[] = {7, 2, 3, 1, 5, 6, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int min = INT_MAX, max = INT_MIN;

// Start time
clock_t start = clock();

findMinAndMax(arr, 0, n - 1, &min, &max);

// End time
clock_t end = clock();

// Calculate time taken


double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;

printf("Minimum element: %d\n", min);


printf("Maximum element: %d\n", max);
printf("Time taken: %f seconds\n", time_taken);
return 0;
}

OUTPUT:

Minimum element: 1
Maximum element: 7
Time taken: 0.000001 seconds

RESULT:
Thus the C program for find out the maximum and minimum numbers in a given list of n numbers
using the divide and conquer technique was executed and verified successfully.
EX.NO:12(A) IMPLEMENTATION OF MERGE SORT

DATE :

AIM: To Implement Merge sort method to sort an array of elements and determine the time
required to sort. Repeat the experiment for different values of n, the number of elements inthe
list to be sorted and plot a graph of the time taken versus n.

ALGORITHM :

Step 1: Define merge_sort() and merge() functions to recursively sort and combine
array halves.
Step 2: Generate a list of random numbers using rand() for different lengths.
Step 3: Measure sorting time using clock() before and after applying merge_sort().
Step 4: Test merge_sort() on arrays of varying sizes to observe time changes.
Step 5: Record sorting times for each array size in a structured format.
Step 6: Export recorded times to a file and plot them using a tool like gnuplot.
Step 7: Analyze the graph to understand merge sort's time complexity.
Step 8: Optionally compare merge sort’s performance with other sorting algorithms.
Step 9: Optimize the implementation based on performance analysis.
Step 10: Document and summarize the results and insights from the tests and analysis.
PROGRAM:

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

// Function to merge two subarrays


void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];

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


L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

int 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++;
}
}

// Function to implement merge sort


void mergeSort(int arr[], int left, int right) {
if (left < right)
{
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);


}
}

// Function to print the array


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

int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Given array: ");


printArray(arr, n);

// Start time
clock_t start = clock();

// Sort the array


mergeSort(arr, 0, n - 1);

// End time
clock_t end = clock();

// Calculate time taken


double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;

printf("Sorted array: ");


printArray(arr, n);

printf("Time taken to sort: %f seconds\n", time_taken);

return 0;
}
OUTPUT:

Given array: 12 11 13 5 6 7
Sorted array: 5 6 7 11 12 13
Time taken to sort: 0.000002 seconds

RESULT:

Thus the C program for Implementation of Merge sort method to sort an array of elements
and determine the time required to sort. Repeat the experiment for different values of n, the
number of elements in the list to be sorted was executed and verified successfully.
EX.NO:12(B) IMPLEMENTATION OF QUICK SORT

DATE :

AIM: To Implement Quick sort method to sort an array of elements and determine the time
required to sort. Repeat the experiment for different values of n, the number of elements in the
list to be sorted and plot a graph of the time taken versus n.

ALGORITHM:

Step1: This program generates a list of random integers of size n , sorts the list using the quicksort
function, and measures the time required to sort the list.

Step2: It repeats this process num_repeats times and returns the average time taken.

Step3: The main function of the program tests the measure_time function for different values of n
and plots a graph of the time taken versus n.

Step4: The maximum value of n is set to max_n, and the step size between values of n is set to
step_size .

Step5: The program uses the built-in random and time modules to generate random integers and
measure time, respectively. Additiona lly, the quicksort function is implemented recursively and
sorts the list in ascending order.

PROGRAM:

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

// Function to swap two elements


void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}

// Partition function
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1); }
// QuickSort function
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


quickSort(arr, pi + 1, high);
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Given array: ");


printArray(arr, n);

// Start time
clock_t start = clock();

// Sort the array


quickSort(arr, 0, n - 1);

// End time
clock_t end = clock();

// Calculate time taken


double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;

printf("Sorted array: ");


printArray(arr, n);

printf("Time taken to sort: %f seconds\n", time_taken);

return 0;

}
OUTPUT:

Given array: 10 7 8 9 1 5
Sorted array: 1 5 7 8 9 10
Time taken to sort: 0.000002 seconds

RESULT:
Thus the implementation of Quick sort method to sort an array of elements and determine the
time required to sort. Repeat the experiment for different values of n, the number of elements
in the list to be sorted was executed and verified successfully.
EX.NO:13 IMPLEMENTATION OF N QUEENS PROBLEM USING BACKTRACKING
DATE :

AIM: To Implement N Queens problem using Backtracking.

ALGORITHM:

Step1: The is_safe function checks whether a queen can be placed in the current cell without
conflicting with any other queens on the board.

Step2: The solve_n_queens function places queens one by one in each column, starting from the
leftmost column. If all queens are placed successfully, it returns True. Otherwise, it backtracks and
removes the queen from the current cell and tries to place it in a different row in the same column.

Step3: The print_board function prints the final board configuration after all queens have been
placed.

Step4: The n_queens function initializes the board and calls the solve_n_queens function to solve
the N Queens problem. If a solution exists, it prints the board configuration. Otherwise, it prints a
message indicating that a solution does not exist.

PROGRAM:

#include <stdio.h>

#include <stdbool.h>

#include <time.h>

#define N 8 // You can change the value of N to solve for different board sizes

// Function to print the solution

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

}
// Function to check if a queen can be placed on board[row][col]

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;

// Recursive utility function to solve N Queens problem

bool solveNQUtil(int board[N][N], int col) {

// If all queens are placed, return true

if (col >= N)

return true;

// Consider this column and try placing this queen in all rows one by one

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

if (isSafe(board, i, col)) {
board[i][col] = 1;

// Recur to place the rest of the queens

if (solveNQUtil(board, col + 1))

return true;

// If placing queen in board[i][col] doesn't lead to a solution, remove queen

board[i][col] = 0; // backtrack

// If the queen cannot be placed in any row in this column, return false

return false;

// Function to solve the N Queens problem using backtracking

bool solveNQ() {

int board[N][N] = { {0} };

if (!solveNQUtil(board, 0)) {

printf("Solution does not exist");

return false;

printSolution(board);

return true;

int main() {

// Start time

clock_t start = clock();

solveNQ();

// End time

clock_t end = clock();

double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;


printf("Time taken to solve: %f seconds\n", time_taken);

return 0;

OUTPUT:

1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0
Time taken to solve: 0.000001 seconds

RESULT:
Thus the C program for Implementation of N Queens problem using BacktrackingTechnique was
executed and verified successfully.
EX.NO:14 IMPLEMENTATION OF ANY SCHEME TO FIND THE OPTIMAL
SOLUTION FOR THE TRAVELING SALESPERSON PROBLEM
DATE :

AIM: To Implement any scheme to find the optimal solution for the Traveling Salesperson problem
and then solve the same problem instance using any approximation algorithm and determine the error
in the approximation.

ALGORITHM:

The following steps involved in solving TSP using branch and bound:
1. Construct a complete graph with the given cities as vertices, where the weight of each edge is
the distance between the two cities.
2. Initialize the lower bound to infinity and create an empty path.
3. Choose a starting vertex and add it to the path.
4. For each remaining vertex, compute the lower bound for the path that includes this vertex and
add it to the priority queue.
5. While the priority queue is not empty, select the path with the lowest lower bound and extend it
by adding the next vertex.
6. Update the lower bound for the new path and add it to the priority queue.
7. If all vertices have been added to the path, update the lower bound to the length of the complete
tour and update the optimal tour if the new tour is shorter.
8. Backtrack to the previous vertex and explore other paths until all paths have been explored.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define POP_SIZE 100


#define GENERATIONS 500
#define MUTATION_RATE 0.01
#define NUM_CITIES 5

typedef struct {
int route[NUM_CITIES];
double fitness;
} Individual;

double distance_matrix[NUM_CITIES][NUM_CITIES];
Individual population[POP_SIZE];

double calculate_distance(int city1[], int city2[]) {


return sqrt(pow(city1[0] - city2[0], 2) + pow(city1[1] - city2[1], 2));
}

void create_distance_matrix(int cities[][2]) {


for (int i = 0; i < NUM_CITIES; i++) {
for (int j = i + 1; j < NUM_CITIES; j++) {
distance_matrix[i][j] = calculate_distance(cities[i], cities[j]);
distance_matrix[j][i] = distance_matrix[i][j];
}
}
}

double route_length(int route[]) {


double length = 0;
for (int i = 0; i < NUM_CITIES - 1; i++) {
length += distance_matrix[route[i]][route[i + 1]];
}
length += distance_matrix[route[NUM_CITIES - 1]][route[0]];
return length;
}

void initialize_population() {
for (int i = 0; i < POP_SIZE; i++) {
for (int j = 0; j < NUM_CITIES; j++) {
population[i].route[j] = j;
}
for (int j = NUM_CITIES - 1; j > 0; j--) {
int k = rand() % (j + 1);
int temp = population[i].route[j];
population[i].route[j] = population[i].route[k];
population[i].route[k] = temp;
}
population[i].fitness = 1.0 / route_length(population[i].route);
}
}

Individual select_parent() {
double total_fitness = 0;
for (int i = 0; i < POP_SIZE; i++) {
total_fitness += population[i].fitness;
}
double rand_point = (double)rand() / RAND_MAX * total_fitness;
double cumulative_fitness = 0;
for (int i = 0; i < POP_SIZE; i++) {
cumulative_fitness += population[i].fitness;
if (cumulative_fitness >= rand_point) {
return population[i];
}
}
return population[POP_SIZE - 1];
}

void crossover(int parent1[], int parent2[], int child[]) {


int start = rand() % NUM_CITIES;
int end = rand() % NUM_CITIES;
if (start > end) {
int temp = start;
start = end;
end = temp;
}
for (int i = 0; i < NUM_CITIES; i++) {
child[i] = -1;
}
for (int i = start; i <= end; i++) {
child[i] = parent1[i];
}
int child_index = 0;
for (int i = 0; i < NUM_CITIES; i++) {
int city = parent2[i];
int found = 0;
for (int j = start; j <= end; j++) {
if (child[j] == city) {
found = 1;
break;
}
}
if (!found) {
while (child[child_index] != -1) {
child[child_index]++;
}
child[child_index++] = city;
}
}
}

void mutate(int route[]) {


for (int i = 0; i < NUM_CITIES; i++) {
if ((double)rand() / RAND_MAX < MUTATION_RATE) {
int j = rand() % NUM_CITIES;
int temp = route[i];
route[i] = route[j];
route[j] = temp;
}
}
}
void genetic_algorithm() {
Individual new_population[POP_SIZE];
for (int gen = 0; gen < GENERATIONS; gen++) {
for (int i = 0; i < POP_SIZE; i++) {
Individual parent1 = select_parent();
Individual parent2 = select_parent();
crossover(parent1.route, parent2.route, new_population[i].route);
mutate(new_population[i].route);
new_population[i].fitness = 1.0 / route_length(new_population[i].route);
}
for (int i = 0; i < POP_SIZE; i++) {
population[i] = new_population[i];
}
}
}

Individual find_best_individual() {
Individual best_individual = population[0];
for (int i = 1; i < POP_SIZE; i++) {
if (population[i].fitness > best_individual.fitness) {
best_individual = population[i];
}
}
return best_individual;
}

int main() {
srand(time(NULL));

int cities[NUM_CITIES][2] = {
{0, 0},
{1, 5},
{5, 5},
{6, 2},
{8, 3}
};
create_distance_matrix(cities);
initialize_population();

clock_t start = clock();


genetic_algorithm();
clock_t end = clock();
Individual best_individual = find_best_individual();
double best_length = 1.0 / best_individual.fitness;
printf("Best route: ");
for (int i = 0; i < NUM_CITIES; i++) {
printf("%d ", best_individual.route[i]);
}
printf("\nLength of the best route: %f\n", best_length);
printf("Running time: %f seconds\n", (double)(end - start) / CLOCKS_PER_SEC);

return 0;
}

OUTPUT:

Best route: 0 2 3 1 4

Length of the best route: 17.698150

Running time: 0.005432 seconds

RESULT:
Thus the python program for implementation of any scheme to find the optimal solution for the
Traveling Salesperson problem and then solve the same problem instance using any approximation
algorithm and determine the error in the approximation was executed and verified successfully.
EX.NO:15 IMPLEMENTATION OF RANDOMIZED ALGORITHMS FOR FINDING
THE KTH SMALLEST NUMBER
DATE :

AIM: To Implement randomized algorithms for finding the kth smallest number.

ALGORITHM:
1. The partition() function takes an array arr , low index low, and high index high as input and
partitions the array around a randomly chosen pivot. It returns the index of the pivot element.
2. The randomized_select() function takes an array arr, low index low, high index high, and the
value of k as input and returns the kth smallest element in the array. It first selects a random pivot
element using random.randint() function and partitions the array using the partition() function.
Then it recursively calls itself on either the left or right partition depending on the position of the
pivot element.
3. In the main section, we define an array arr and the value of k. Then we calculate the length of the
array n and call the randomized_select() function on the array to find the kth smallest element.

PROGRAM:

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

// Swap function
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Partition function similar to Quicksort


int partition(int arr[], int left, int right) {
int pivotIndex = left + rand() % (right - left + 1);
int pivotValue = arr[pivotIndex];
swap(&arr[pivotIndex], &arr[right]); // Move pivot to end
int storeIndex = left;

for (int i = left; i < right; i++) {


if (arr[i] < pivotValue) {
swap(&arr[i], &arr[storeIndex]);
storeIndex++;
}
}
swap(&arr[storeIndex], &arr[right]); // Move pivot to its final place
return storeIndex;
}

// Quickselect function
int quickselect(int arr[], int left, int right, int k) {
if (left == right) {
return arr[left];
}

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

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

int main() {
srand(time(NULL)); // Seed the random number generator

int arr[] = {12, 3, 5, 7, 4, 19, 26};


int n = sizeof(arr) / sizeof(arr[0]);
int k = 3; // We are looking for the 3rd smallest number (0-based index)

if (k >= 0 && k < n) {


clock_t start = clock();
int result = quickselect(arr, 0, n - 1, k);
clock_t end = clock();

printf("The %d-th smallest element is %d\n", k + 1, result);


printf("Running time: %f seconds\n", (double)(end - start) / CLOCKS_PER_SEC);
} else {
printf("k is out of bounds\n");
}

return 0;
}
OUTPUT:

The 3-th smallest element is 7


Running time: 0.000008 seconds

RESULT:
Thus the C program for implementation of randomized algorithms for finding the kthsmallest number was
executed and verified successfully.

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy