Algorithms Lab
Algorithms Lab
Name:
Reg.No:
Department:
Year/Sem:
INDEX
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>
int main() {
int size;
int target;
OUTPUT:
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 :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int size;
int target;
if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found\n");
}
return 0;
}
OUTPUT:
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.
PROGRAM:
#include <stdio.h>
#include <string.h>
#include <time.h>
// If pattern matches
if (j == M) {
printf("Pattern found at index %d\n", i);
}
}
}
int main() {
char text[] = "ABABDABACDABABCABAB";
char pattern[] = "ABABCABAB";
start = clock();
naiveStringMatching(pattern, text);
end = clock();
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:
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 .
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;
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
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
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
start = clock();
heapSort(arr, n);
end = clock();
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 :
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.
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);
return graph;
}
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
while (!isEmpty(q)) {
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);
// Main function
int main() {
struct Graph* graph = createGraph(6);
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
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 :
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.
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;
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;
int main() {
struct Graph* graph = createGraph(4);
printf("Graph representation:\n");
printGraph(graph);
return 0;
}
OUTPUT:
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>
distance[start] = 0;
visited[start] = 1;
count = 1;
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:
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 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>
return min_index;
}
key[0] = 0;
parent[0] = -1;
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 :
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
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:
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;
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();
// End time
clock_t end = clock();
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>
int i = 0, j = 0, k = left;
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
// Start time
clock_t start = clock();
// End time
clock_t end = clock();
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>
// Partition function
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// Start time
clock_t start = clock();
// End time
clock_t end = clock();
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 :
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
printf("\n");
}
// Function to check if a queen can be placed on board[row][col]
int i, j;
if (board[row][i])
return false;
if (board[i][j])
return false;
if (board[i][j])
return false;
return true;
if (col >= N)
return true;
// Consider this column and try placing this queen in all rows one by one
if (isSafe(board, i, col)) {
board[i][col] = 1;
return true;
board[i][col] = 0; // backtrack
// If the queen cannot be placed in any row in this column, return false
return false;
bool solveNQ() {
if (!solveNQUtil(board, 0)) {
return false;
printSolution(board);
return true;
int main() {
// Start time
solveNQ();
// End time
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>
typedef struct {
int route[NUM_CITIES];
double fitness;
} Individual;
double distance_matrix[NUM_CITIES][NUM_CITIES];
Individual population[POP_SIZE];
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];
}
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();
return 0;
}
OUTPUT:
Best route: 0 2 3 1 4
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;
}
// Quickselect function
int quickselect(int arr[], int left, int right, int k) {
if (left == right) {
return arr[left];
}
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
return 0;
}
OUTPUT:
RESULT:
Thus the C program for implementation of randomized algorithms for finding the kthsmallest number was
executed and verified successfully.