Algorithm Record
Algorithm Record
No: 1
IMPLEMENT LINEAR SEARCH
Date:
AIM:
To implement Linear search and determine the time required to search an element and plot a graph of
time Taken versus n.
ALGORITHM:
Step 1: Start.
Step 4: Create an array with number of elements in the list to find the time taken.
Step 6: Stop.
PROGRAM:
import time
import matplotlib.pyplot as plt
1
# get the elements of the array from the user
arr = []
for i in range(n):
x = int(input(f"Enter element {i}: "))
arr.append(x)
if index != -1:
print(f"Found element {x} at index {index}")
else:
print(f"Element {x} not found")
2
if choice.lower() != 'y':
break
# plot a graph of the time taken versus n
plt.plot(ns, times)
plt.xlabel("Time taken (seconds)")
plt.ylabel("n")
plt.show()
OUTPUT:
Enter the number of elements: 5
Enter element 0: 54
Enter element 1: 76
Enter element 2: 83
Enter element 3: 26
Enter element 4: 54
Enter the element to search for: 76
Found element 76 at index 1
Time taken to search for 76 in array of size 5: 2.1199986804276705e-05 seconds
3
Enter element 1: 28
Enter element 2: 52
Enter element 3: 39
Enter element 4: 65
Enter element 5: 99
Enter the element to search for: 99
Found element 99 at index 5
Time taken to search for 99 in array of size 6: 2.400000812485814e-05 seconds
Do you want to search another array? (y/n) n
RESULT:
4
Ex.No: 2
IMPLEMENT BINARY SEARCH
Date:
AIM:
To implement recursive binary search and determine the time required to search an element and plot a
graph of time Taken versus n.
ALGORITHM:
Step1: Start.
Step 3: Import time module to determine the time taken to search an element.
Step 5: Stop.
PROGRAM:
import time
import matplotlib.pyplot as plt
5
n = int(input("Enter the number of elements: "))
if index != -1:
print(f"Found element {x} at index {index}")
else:
print(f"Element {x} not found")
6
# ask if the user wants to search another array
choice = input("Do you want to search another array? (y/n) ")
if choice.lower() != 'y':
break
OUTPUT:
Enter the number of elements: 5
Enter element 0: 45
Enter element 1: 67
Enter element 2: 34
Enter element 3: 13
Enter element 4: 16
Sorted list: [13, 16, 34, 45, 67]
Enter the element to search for: 45
Found element 45 at index 3
Time taken to search for 45 in array of size 5: 1.5400000847876072e-05 seconds
7
Do you want to search another array? (y/n) y
Enter the number of elements: 5
Enter element 0: 34
Enter element 1: 27
Enter element 2: 16
Enter element 3: 27
Enter element 4: 39
Sorted list: [16, 27, 27, 34, 39]
Enter the element to search for: 27
Found element 27 at index 2
Time taken to search for 27 in array of size 5: 1.379998866468668e-05 seconds
RESULT:
8
Ex.No: 3 Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function search (char pat
Date: [ ], char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume that n > m.
AIM:
To write a program for a text txt[0…n-1] and a pattern pat[0…m-1], using a function search(char pat[],
char txt[]) that prints all occurences of pat[] in txt[].
ALGORITHM:
Step 1: Start.
Step 5: Stop.
PROGRAM:
def search(pat, txt):
m = len(pat)
n = len(txt)
# User interface
def main():
txt = input("Enter the text: ")
pat = input("Enter the pattern to search: ")
9
search(pat, txt)
OUTPUT 2:
RESULT:
The program to implement txt and pat using a function search(char pat[],char txt[]) is executed
successfully.
10
Ex.No: 4
INSERTION SORT & HEAP SORT
Date:
AIM:
To write a program to sort a given set of elements using insertion sort and heap sort and to determine
time requited for sorting pot a graph of time taken vs n.
ALGORITHM:
Step 1: Start.
Step 2: Create the array for sorting.
Step 3: Perform insertion sort and heap sort.
Step 4: Display the time requited for sorting.
Step 5: Plot the graph for time taken vs n.
Step 6: End.
PROGRAM:
import random
import time
import matplotlib.pyplot as plt
# Insertion sort
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Heap sort
def heap_sort(arr):
def heapify(arr, n, i):
largest = i
l=2*i+1
r=2*i+2
if l < n and arr[l] > arr[largest]:
largest = l
11
if r < n and arr[r] > arr[largest]:
largest = r
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
# Initialize lists to store values of n and time taken for each algorithm
n_values = []
insertion_sort_times = []
heap_sort_times = []
# Prompt the user for permission to perform multiple sorting operations
while True:
choice = input("Do you want to sort a list? (y/n): ")
if choice.lower() != 'y':
break
# Get input from the user
n = int(input("Enter the number of values in the list: "))
lst = []
for i in range(n):
val = int(input("Enter a value for the list: "))
lst.append(val)
12
end_time = time.perf_counter()
heap_sort_time = end_time - start_time
heap_sort_times.append(heap_sort_time)
OUTPUT:
Do you want to sort a list? (y/n): y
Enter the number of values in the list: 10
Enter a value for the list: 59
Enter a value for the list: 43
Enter a value for the list: 72
Enter a value for the list: 39
Enter a value for the list: 98
Enter a value for the list: 13
Enter a value for the list: 16
Enter a value for the list: 72
Enter a value for the list: 89
Enter a value for the list: 34
Sorted list using Insertion sort: [13, 16, 34, 39, 43, 59, 72, 72, 89, 98]
Time taken by Insertion sort: 0.000023 seconds
13
Sorted list using Heap sort: [13, 16, 34, 39, 43, 59, 72, 72, 89, 98]
Time taken by Heap sort: 0.000031 seconds
RESULT:
Thus, the program has been executed successfully.
14
Ex.No: 5
GRAPH TRAVERSAL - BREADTH FIRST SEARCH
Date:
AIM:
ALGORITHM:
Step 1: Start.
Step 2: Put any one of the graph’s vertices at the back of the queue.
Step 3: Take the front item of the queue and add it to the visited list.
Step 4: Create a list of that vertex's adjacent nodes. Add those which are not within the visited list tothe rear of
the queue.
Step 5: Keep continuing steps two and three till the queue is empty.
Step 6: Stop.
PROGRAM:
15
visited.add(node)
print(node, end=' ')
if node in self.graph:
for neighbour in self.graph[node]:
queue.append(neighbour)
# Get graph input from the user
g = Graph()
n = int(input("Enter the number of edges: "))
for i in range(n):
u, v = input("Enter edge {}: ".format(i+1)).split()
g.add_edge(u,v)
OUTPUT:
RESULT:
Thus, graph traversal using Breadth First Search has been implemented successfully.
16
Ex.No: 6
GRAPH TRAVERSAL - DEPTH FIRST SEARCH
Date:
AIM:
ALGORITHM:
Step 1: Start.
Step 2: Put any one of the graph's vertex on top of the stack.
Step 3: Take the top item of the stack and add it to the visited list of the vertex.
Step 4: Create a list of that adjacent node of the vertex. Add the ones which aren't in the visited list of
vertexes to the top of the stack.
Step 5: Keep repeating steps 2 and 3 until the stack is empty.
Step 6: Stop.
PROGRAM:
17
# Get starting node input from the user
start = input("Enter the starting node: ")
OUTPUT:
RESULT:
Thus, graph traversal using Depth First Search has been implemented successfully.
18
Ex.No: 7
IMPLEMENTATION OF DIJKSTRA’S ALGORITHM
Date:
AIM:
To implement a python program to find the shortest paths to other vertices using dijkstra’s algorithm.
ALGORITHM:
Step 1: Start.
Step 2: Mark all vertex as unvisited.
Step 3: Mark source vertex as 0 and other vertex as infinity.
Step 4: Calculate the path length of all neighbor nodes from current adding the weight of
edges.
Step 5: Now new path is smaller than previous path then replace it.
Step 6: Mark the current vertex as visited after moving to its neighbor.
Step 7: Choose the path which is having smallest path length and go to step 3.
Step 8: Repeat the steps until all vertices are visited.
Step 9: Stop.
PROGRAM:
import heapq
def dijkstra(graph, start):
# Initialize distances to all nodes as infinity except the starting node
distances = {node: float('inf') for node in graph}
distances[start] = 0
# Use a priority queue to keep track of the next closest node to visit
pq = [(0, start)]
while pq:
# Get the node with the smallest distance from the start
current_dist, current_node = heapq.heappop(pq)
# If we've already visited this node with a shorter distance, skip it
if current_dist > distances[current_node]:
continue
# For each neighbor of the current node, calculate the new distance
for neighbor, weight in graph[current_node].items():
19
new_dist = current_dist + weight
# If the new distance is shorter than the current distance, update it
if new_dist < distances[neighbor]:
distances[neighbor] = new_dist
heapq.heappush(pq, (new_dist, neighbor))
return distances
20
OUTPUT:
Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): A,B,4 A,C,5 B,C,11 B,E,7
B,D,9 C,E,3 D,E,13 D,F,2 E,F,6
RESULT:
21
Ex.No: 8
IMPLEMENTATION OF PRIMS ALGORITHM
Date:
AIM:
ALGORITHM:
Step 1: Start
Step 4: Create a priority queue Q and add all edges incident to v to Q, with their weights as keys.
ii. If both vertices of the edge are visited, ignore the edge and continue to the next one.
Iii. Otherwise, mark the unvisited vertex as visited, add the edge to the MST, and add all edges incident
to the new vertex to Q.
Step 8: Stop
PROGRAM:
import heapq
# Initialize the dictionary that will keep track of the shortest edge to each node
shortest_edges = {node: (float('inf'), None) for node in graph}
shortest_edges[start] = (0, start)
22
# Use a priority queue to keep track of the next closest edge to visit
pq = [(0, start)]
while unvisited:
# Get the edge with the smallest weight
current_weight, current_node = heapq.heappop(pq)
# Mark the current node as visited and remove it from the set of unvisited nodes
visited.add(current_node)
unvisited.remove(current_node)
# For each neighbor of the current node, update the shortest edge to that neighbor
for neighbor, weight in graph[current_node].items():
if neighbor not in unvisited:
continue
if weight < shortest_edges[neighbor][0]:
shortest_edges[neighbor] = (weight, current_node)
heapq.heappush(pq, (weight, neighbor))
# Print the sum of the shortest distance and the shortest path to each node
print("Sum of the shortest distance and the shortest path to each node:")
for node in shortest_edges:
distance = shortest_edges[node][0]
path = []
while node != start:
path.insert(0, node)
node = shortest_edges[node][1]
path.insert(0, start)
print("{}: {} ({})".format(node, distance, "->".join(path)))
23
# Ask the user to input the graph as a list of edges
edges = input("Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): ").split()
graph = {}
for edge in edges:
node1, node2, weight = edge.split(',')
weight = int(weight)
if node1 not in graph:
graph[node1] = {}
if node2 not in graph:
graph[node2] = {}
graph[node1][node2] = weight
graph[node2][node1] = weight # since it's an undirected graph
# Use Prim's algorithm to find the shortest distance and path to each node in the graph
prims(graph, start)
OUTPUT:
Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): A,B,4 A,C,4 B,C,2 C,D,3 C,E,2
C,F,4 D,F,3 E,F,3
Enter the starting node: A
Sum of the shortest distance and the shortest path to each node:
A: 0 (A)
A: 4 (A->B)
A: 2 (A->B->C)
A: 3 (A->B->C->D)
A: 2 (A->B->C->E)
A: 3 (A->B->C->E->F)
RESULT:
24
Ex.No: 9 IMPLEMENT FLOYD’S ALGORITHM FOR THE ALL-PAIRS
AIM:
ALGORITHM:
Step 1:Start
Step 3: Traverse through each of the intermediates i.e from vertex to destination.
Step 4: Once all the nodes are traversed, compare and select the shortest path.
Step 5: End
PROGRAM:
def floyd(graph):
# Create a copy of the graph dictionary to avoid modifying the original
graph = graph.copy()
25
if graph[i][j] > graph[i][k] + graph[k][j]:
graph[i][j] = graph[i][k] + graph[k][j]
26
OUTPUT:
Enter the edges of the graph in the format 'node1,node2,weight' (separated by spaces): 0,2,-2 1,0,4 1,2,3
2,3,2 3,1,-1
Shortest paths:
0 -> 0: 0
0 -> 1: -1
0 -> 2: -2
0 -> 3: 0
1 -> 0: 4
1 -> 1: 0
1 -> 2: 2
1 -> 3: 4
2 -> 0: 5
2 -> 1: 1
2 -> 2: 0
2 -> 3: 2
3 -> 0: 3
3 -> 1: -1
3 -> 2: 1
3 -> 3: 0
RESULT:
The program to implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problemhas been executed
successfully.
27
Ex.No: 10
WARSHALL ALGORITHM
Date:
AIM:
To write a python program to compute the transitive closure of a given directed graph using Warshall's
algorithm.
ALGORITHM:
Step 1: Start
Step 6: Stop
PROGRAM:
def transitive_closure(graph):
n = len(graph)
tc = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
tc[i][j] = graph[i][j]
for k in range(n):
for i in range(n):
for j in range(n):
tc[i][j] = tc[i][j] or (tc[i][k] and tc[k][j])
return tc
28
n = int(input("Enter number of vertices: "))
graph = []
for i in range(n):
row = list(map(int, input(f"Enter row {i+1}: ").split()))
graph.append(row)
RESULT:
29
Ex.No: 11
DIVIDE AND CONQUER TECHNIQUE
Date:
AIM:
To write a python program to find out the maximum and minimum numbers in a given list of n numbers
using the divide and conquer technique.
ALGORITHM:
Step 1 : Start.
Step 2 : Define a function called max_min that takes a list of numbers as input.
Step 3 : If the length of the input list is 1, return a tuple with the single number as both the maximum
and minimum value.
Step 4 : If the length of the input list is 2, compare the two numbers and return a tuple with the
maximum and minimum values.
Step 5 : If the length of the input list is greater than 2, split the list in half and recursively call the
max_min function on each half.
Step 6 : For each recursive call, store the maximum and minimum values of the left half and the
maximum and minimum values of the right half in separate variables.
Step 7 : Compare the maximum values of the left and right halves, and return the larger value as the
maximum value for the entire list.
Step 8 : Compare the minimum values of the left and right halves, and return the smaller value as the
minimum value for the entire list.
Step 9 : Call the max_min function on the entire input list, and print the maximum and minimum values
returned by the function.
Step 10 : Stop.
PROGRAM:
def max_min(nums):
if len(nums) == 1:
return (nums[0], nums[0])
elif len(nums) == 2:
30
return (max(nums[0], nums[1]), min(nums[0], nums[1]))
else:
mid = len(nums) // 2
left_max, left_min = max_min(nums[:mid])
right_max, right_min = max_min(nums[mid:])
return (max(left_max, right_max), min(left_min, right_min))
RESULT:
Thus the program to find out the maximum and minimum numbers in a given list of n numbers using the
divide and conquer technique was implemented succussfully.
31
Ex.No: 12
MERGE SORT & QUICK SORT
Date:
AIM:
To write a program to sort a given set of elements using merge sort and quick sort and to determine time
requited for sorting pot a graph of time taken vs n.
ALGORITHM:
Step 1 : Start
Step 2 : Define a function for merge sort that recursively divides a list into smaller sublists and merges
them together in sorted order.
Step 3 : Define a function for quick sort that recursively partitions a list into two sublists based on a
pivot value, and sorts each sublist separately.
Step 4 : Initialize empty lists to store values of n and time taken for each algorithm.
Step 5 : Prompt the user for permission to perform multiple sorting operations using a while loop.
Step 6 : Get input from the user for the number of values in the list and the values themselves.
Step 7 : Measure time for merge sort and quick sort using the time.perf_counter() function.
Step 8 : Append the time taken by each algorithm to their respective lists.
Step 10:Print the sorted list and the time taken by each algorithm and Plot the graph of time taken versus
n for each algorithm using matplotlib.pyplot.
PROGRAM:
import time
import matplotlib.pyplot as plt
# merge sort
def merge_sort(lst):
if len(lst) > 1:
mid = len(lst) // 2
left_half = lst[:mid]
right_half = lst[mid:]
32
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
33
greater.append(item)
else:
lesser.append(item)
return quick_sort(lesser) + [pivot] + quick_sort(greater)
# Initialize lists to store values of n and time taken for each algorithm
n_values = []
merge_sort_times = []
quick_sort_times = []
start_time = time.perf_counter()
quick_sort(lst)
end_time = time.perf_counter()
34
quick_sort_time = end_time - start_time
quick_sort_times.append(quick_sort_time)
# Print the sorted list and the time taken by each algorithm
print("Sorted list using merge sort:", lst)
print("Time taken by merge sort: {:.6f} seconds".format(merge_sort_time))
print("Sorted list using quick sort:", lst)
print("Time taken by quick sort: {:.6f} seconds".format(quick_sort_time))
35
Do you want to sort a list? (y/n): y
Enter the number of values in the list: 8
Enter a value for the list: 23
Enter a value for the list: 76
Enter a value for the list: 98
Enter a value for the list: 45
Enter a value for the list: 33
Enter a value for the list: 12
Enter a value for the list: 45
Enter a value for the list: 27
Sorted list using merge sort: [12, 23, 27, 33, 45, 45, 76]
Time taken by merge sort: 0.000028 seconds
Sorted list using quick sort: [12, 23, 27, 33, 45, 45, 76]
Time taken by quick sort: 0.000018 seconds
Do you want to sort a list? (y/n): y
Enter the number of values in the list: 9
Enter a value for the list: 54
Enter a value for the list: 98
Enter a value for the list: 56
Enter a value for the list: 24
Enter a value for the list: 10
Enter a value for the list: 85
Enter a value for the list: 36
Enter a value for the list: 29
Enter a value for the list: 78
Sorted list using merge sort: [10, 24, 29, 36, 54, 56, 78, 85]
Time taken by merge sort: 0.000035 seconds
Sorted list using quick sort: [10, 24, 29, 36, 54, 56, 78, 85]
Time taken by quick sort: 0.000017 seconds
Do you want to sort a list? (y/n): n
RESULT:
Thus, the program has been executed successfully.
36
Ex.No: 13
N-QUEEN PROBLEM
Date:
AIM:
To write a program to Implement N Queens problem using Backtracking.
ALGORITHM:
Step 1 : Start.
Step 2 : Initialize an empty NxN chessboard.
Step 3 : Start with the first row (row 0).
Step 4 : Try to place a queen in each column of the current row, one by one.
Step 5 : For each column, check if it's safe to place the queen at the current position.
Step 6 : If it's safe, mark the current cell as occupied by a queen, and move to the next row (row 1).
Step 7 : Repeat steps 3-5 recursively for each row until all N queens are placed on the board.
Step 8 : If all N queens are successfully placed, print the board as the solution.
Step 9 : If it's not possible to place a queen in any column of the current row, backtrack to the previous
row and try to place the queen in a different column.
Step 10 : If all columns of all rows have been tried and no solution is found, return "No solution exists".
Step 11 : Stop.
PROGRAM:
def is_safe(board, row, col, n):
for i in range(row):
if board[i][col] == 1:
return False
i = row
j = col
while i >= 0 and j >= 0:
if board[i][j] == 1:
return False
i -= 1
j -= 1
i = row
j = col
while i >= 0 and j < n:
37
if board[i][j] == 1:
return False
i -= 1
j += 1
return True
def solve_n_queens(board, row, n):
if row == n:
return True
for col in range(n):
if is_safe(board, row, col, n):
board[row][col] = 1
if solve_n_queens(board, row + 1, n):
return True
board[row][col] = 0
return False
def print_board(board):
for row in board:
print(" ".join(str(cell) for cell in row))
n = int(input("Enter the value of N: "))
board = [[0 for x in range(n)] for y in range(n)]
if solve_n_queens(board, 0, n):
print_board(board)
else:
print("No solution found")
OUTPUT:
Enter the value of N: 4
0100
0001
1000
0010
RESULT:
Thus, the program for n-Queen problem using backtracking has been executed successfully.
38
Ex.No: 14
TRAVELLING SALESMAN PROBLEM
Date:
AIM:
To write a program 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:
Step 1 : Start.
Step 2 : Given a complete undirected graph G with n vertices and edge weights w(i,j), construct a
minimum spanning tree T of G.
Step 3 : Let O be the set of vertices with odd degree in T.
Step 4 : Compute a minimum-weight perfect matching M on the vertices in O.
Step 5 : Combine the edges in T and M to form a connected graph H.
Step 6 : Find an Eulerian tour in H, i.e., a cycle that traverses each edge exactly once.
Step 7 : Convert the Eulerian tour into a Hamiltonian tour by skipping repeated vertices, i.e., vertices
that have already been visited.
Step 8 : Output the resulting Hamiltonian tour as the solution to the TSP problem.
Step 9 : Stop.
PROGRAM:
import sys
def least_opt(c):
global cost_opt
nc = sys.maxsize
min = sys.maxsize
kmin = sys.maxsize
for i in range(0, n):
if a[c][i] != 0 and visit[i] == 0:
if a[c][i] < min:
min = a[c][i]
kmin = a[c][i]
nc = i
if kmin != sys.maxsize:
39
cost_opt += kmin
return nc
def least_apr(c):
global cost_apr
nc = sys.maxsize
min = sys.maxsize
kmin = sys.maxsize
for i in range(0, n):
if a[c][i] != 0 and visit[i] == 0:
if a[c][i] < kmin:
min = a[c][i]
kmin = a[c][i]
nc = i
if kmin != sys.maxsize:
cost_apr += kmin
return nc
def mincost_opt(city):
global cost_opt
visit[city] = 1
print(city, end='-->')
ncity = least_opt(city)
if ncity == sys.maxsize:
ncity = 0
print(ncity)
cost_opt += a[city][ncity]
return
mincost_opt(ncity)
def mincost_apr(city):
global cost_apr
visit[city] = 1
40
print(city, end='-->')
ncity = least_apr(city)
if ncity == sys.maxsize:
ncity = 0
print(ncity)
cost_apr += a[city][ncity]
return
mincost_apr(ncity)
print("\nOptimal Solution:")
print("The path is:")
mincost_opt(0)
print("Minimum cost: %d" % cost_opt)
visit = [0] * n
print("\nApproximated Solution:")
print("The path is:")
41
mincost_apr(0)
print("Minimum cost: %d" % cost_apr)
print("Error in approximation is approximated solution/optimal solution = %f" % (cost_apr/cost_opt))
OUTPUT:
Enter No. of cities: 4
Enter the cost matrix:
Enter elements of row 0:
0 10 15 20
Enter elements of row 1:
10 0 35 25
Enter elements of row 2:
15 35 0 30
Enter elements of row 3:
20 25 30 0
The cost list is:
0 10 15 20
10 0 35 25
15 35 0 30
20 25 30 0
Optimal Solution:
The path is:
0-->1-->3-->2-->0
Minimum cost: 80
Approximated Solution:
The path is:
0-->1-->3-->2-->0
Minimum cost: 80
Error in approximation is approximated solution/optimal solution = 1.000000
RESULT:
Thus, the program has been executed successfully.
42
Ex.No: 15
RANDOMISED ALGORITHM TO FIND KTH SMALLEST ELEMENT
Date:
AIM:
To write a program to Implement randomized algorithms for finding the kth smallest number
ALGORITHM:
Step 1 : Start.
Step 2 : If the length of the input array arr is 1, return the only element in the array as the k-th smallest
element.
Step 3 : Choose a random element pivot from the input array arr.
Step 4 : Partition the array arr into three parts: lows, pivots, and highs.
*lows: a list of elements in arr that are less than pivot
*pivots: a list of elements in arr that are equal to pivot
*highs: a list of elements in arr that are greater than pivot
Step 5 : If k is less than the length of lows, the k-th smallest element must be in the lows list.
Recursively call quick_select with lows and k as inputs.
Step 6 : If k is less than the length of lows plus the length of pivots, the k-th smallest element is the pivot.
Return the pivot as the result.
Step 7 : If k is greater than the length of lows plus the length of pivots, the k-th smallest element must be
in the highs list. Recursively call quick_select with highs and k - len(lows) - len(pivots) as inputs.
Step 8 : Return the result of the recursive call to quick_select.
Step 9 : Stop.
PROGRAM:
import random
def quick_select(arr, k):
if len(arr) == 1:
return arr[0]
pivot = random.choice(arr)
lows = [x for x in arr if x < pivot]
highs = [x for x in arr if x > pivot]
pivots = [x for x in arr if x == pivot]
if k < len(lows):
return quick_select(lows, k)
43
elif k < len(lows) + len(pivots):
return pivots[0]
else:
return quick_select(highs, k - len(lows) - len(pivots))
arr = list(map(int, input("Enter array elements separated by space: ").split()))
k = int(input("Enter the value of k: "))
kth_smallest = quick_select(arr, k-1)
print(f"The {k}th smallest number in the array is: {kth_smallest}")
OUTPUT:
RESULT:
Thus, the program to Implement randomized algorithms for finding the kth smallest number has been
executed successfully.
44