Algorithms. Record-1
Algorithms. Record-1
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:
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;
int main()
{
int sizes[]={ 1000, 5000, 10000, 50000, 100000};
int numSizes= sizeof(sizes)/sizeof(sizes[0]);
double timesInsertionSort[numSizes];
double timesHeapSort[numSizes];
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:
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);
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
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:
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]]);
}
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: -
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);
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>
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;
}
swap(&arr[pivotIndex], &arr[right]);
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