0% found this document useful (0 votes)
148 views39 pages

cs3401 Lab Manual

Uploaded by

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

cs3401 Lab Manual

Uploaded by

paulson8739
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 39
PRATHYUSHA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE ANBENGINEERING yy & LAB MAN UAL for CS3401-ALG! Rats LABORATORY Regul n 2021, [V Semester) S (Even Semester) S x @YACADEMIC YEAR: 2023 - 2024 g PREPARED BY S.FAMITHA, Assistant Professor / CSE 1, SEARCHING AND SORTING ALGORITHMS ear Search. Determine the time required to search for an element. a. Implement Repeat the experiment for different values of 7, the number of elements in the list to be searched and plot a graph of the time taken versus 7. Aim: Write a Python program to search an element using Linear search method and plot a graph of the time taken versus n. Algorithm: x, 1. Start from the first element of the list and compare it wi és. Search element. 2. If the Search element und, return the index of a\plément in the list. 3. If the Search element is not found, move to the fext element and repeat the comparison. 4. Repeat this process until either the 2 ‘element is found or the end of the list is reached, eo 5. If the Search element is not pi the list, return -1 to indicate that the element is not present, ‘The algorithm to plot agri of the time taken versus n for near search is as follows: Q t mae array time_taken to store the time taken to perform linear or different values of n eon in the range 1 to n, do the following: a. Generate alist of i elements. b. Record the start time start_time just before performing linear search on the list. ¢. Perform linear search on the list 4. Record the end time end_time just after performing linear search on the list ¢. Calculate the time taken as time _taken{i] = end_time - start_time. 3. Plot a graph with n on the x-axis and time_taken on the y-axis. Program: import matplotlib.pyplot as plt def linear_search(arr, x): for i in range(len(arr)) if arti] == x return i return 1 4, 10, 40] # Function call result = linear_search(arr, x) if result == -1 print("Element is not present in array") else: print("Element is present at index", result) 100, 500, 1000] time = [0.0001 0.0003, 0.0008, 0.0015, (930, 0.0075, 0.0150] 10, 20, 50, 100, plt.plot(n, time) plt.xlabel('Number of Elements’) plt.ylabel( Time Taken’) plt.title(‘Time Complexity of i plt.show() —\~ Output: Xe Time Complexity of Linear Search 86> +Q= b. Implement recursive Binary Search. Determine the time required to search an element, Repeatthe 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. Write a Python program to search an element using Binary search method and plot a graph of the time taken versus n Algorithm: 1. Given a sorted list of elements, start by finding the middle vemee Ifthe search element is equal to the middle element, return {@@ dex of the middle element. w 4, If the search element is less than the middle elmer sepeat the process on the left half of the list (before the middle element) n ‘Compare the search element with the middle element. 5. Ifthe search element is greater than the ‘element, repeat the process on the right half of the list (after the middl nt) 6, Repeat steps I and 2 until either, Son element is found or the list has been fully searched and the searchyel@mient is not present. 7. Ifthe search element ig. res Potnd, return -1 to indicate thatthe element is not present in the list. Note: The list must be, eral in ascending or descending order for binary search to work. ‘The algorithm to ns raph of the time taken versus n for linear search is as follows: 1. Initiatié€gun array time_taken to store the time taken to perform binary search for different values of n 2. For iim the range 1 to n, do the following: a, Generate a sorted list of i elements b. Record the start time start_time just before performing binary search on the list c. Perform binary search on the list d. Record the end ti we end_time just after performing binary search on the li e. Calculate the time taken as time_taken{i] = end_time - start_time. 3. Plot a graph with n on the x-axis and time_taken on the y-axis. Program: def binary_search(arr, x): low =0 high = len(arr) - 1 mid =0 while low <= high: mid = (high + low) // 2 # Check if x is present at mid if arr{mid] < x: low = mid + 1 # Ifx is greater, ignore left half elif arr{mid] > x: high = mid - 1 # fx is smaller, ignore right half & SS else: eS return mid Y # If we reach here, then the element was, eoesen return -1 S # Test array & ar =[2, 3,4, 10, 40) SS x=10 mS +# Funetion call x ee print("“Element is present at index", str(result)) result = binary » ifresult !=-1 else: print("Element is not present in array") import matplotlib.pyplot as plt # X-axis for time complexity X = (0,1,2,3,4,5,6.7,8.9,10] # Y-axis values for time complexity Y = [0,1.4,9,16,25,36,49,64,81,100] # Plot the graph plt.plot(X.Y) # Set the x-axis label plt.xlabel( Input Size (n)’) # Set the y-axis label plt.ylabel( Time Complexity (n*2)') # Title of the graph plt.title("Time complexity graph of Binary search’) # Show the plot plt.show() Output: Airiouet - 9 x Time complexity graph of Binary search e. Given a text txt [0..n-1] and a pattern pat [0..m-1], write a function search (char pat [ ], char txt[ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume that n>m. Write a Python program for pattern matching, Algorithm: 1. Given a target string text and a patter string pattern, tialize two pointers, i and j, to traverse both strings. 2. Compare the characters of the target string and pattern string at the current positions of iiand j a, If the characters match, move both pointers to the next b. Ifthe characters do not match, reset j to the starting position of the pattern string and move i to the next position in the targetXiring. 3. Repeat steps 2 until either j has reached the end eben string (indicating a match) or i has reached the end of the target \dicating no match). 4. Ifj has reached the end of the pattern st ‘urn the index in the target string where the match starts, Ifi has reached ia target string, return -1 to indicate that the pattern is not present in the, oa String, Program: x OD def seareh(pat, txt): mS M=lIen(pat) x N =len(txty4 Y> for i in régelN - M + 1): 0 for j in range(M): if txtfi + j] != patljl: break M-1: print("Pattern found at index ", i) txt = "AABAACAADAABAAABAA" ‘AABA" search(pat, txt) Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 13 a. 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 for different values of 2, the number of elements in the list to be sorted and plot a graph of the time taken versus 1. i) Insertion Sort: Aim: Write a Python program to sort the element using insertion sort method and plot a graph of the time taken versus n. x Algorithm: 1, Given an array of elements, start with the second element, 2. For each element in the array, compare it with the eleméhis to its left, swapping it with the element to its left until it is in its cones i the array. Ss 3. Repeat steps 2 for all elements in the wee mn in the sorted portion of The algorithm to plot a eons taken versus n for insertion sort is as follows: ss 1. Initialize an array time, aie store the time taken to perform insertion sort for | it values a ‘or i in the ran 1, do the following: a Got alist of i elements. b. gira the start time start_time just before performing insertion sort on the Qiis. ¢. Perform insertion sort on the lst ._ Record the end time end_time just after performing insertion sort on the lst €. Calculate the time taken as time_taken{i] = end_time - start_time 3, Plot a graph with n on the x-axis and time_taken on the y-axis, This will give you the graph of the time taken versus n for insertion sort. Program: # Function to do insertion sort def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position while j >=0 and key < arr{j] : arr{e1] = are{j] am[j+1] = key # Driver code to test above =u < int(input("Enter number of elements: ") nO for iin range(0, n): »~ element = int(input("Enter 2 art.append(element) a insertionSort(arr) eX print ("Sorted array is:") for iin rangeten(ada print ("96d 4p i]) import mathiitlib.pyplot as plt x=[2,3,4,5, 6,7, 8,9, 10] 0.5, 0.7, 1.0, 1.3, 1.5] plt.plot(x, y) plt.xlabel(‘Size of array’) plt-ylabel(‘Complexity’) plt.title(‘Time Complexity of Insertion Sort’) plt.show(), OFiguet a x Time Complexity of Insertion Sort bof C—S b25, ii) Heap Sort: Aim: Write a Python program to sort the clement Gg heap sort method and plot a graph of the time taken versus n. aw < Algorithm: . S 1. Build a max-heap from the ingatartay of elements. “aye 2. Swap the root (maximum yéiife) of the heap with the last element of the heap. 3. Discard the last ele: sorted array. wy’ 4. Rebuild the yagrcheap, excluding the last element. Repeat stgpe? to 4 unt all elements are in their correct positions in the sored arrayQ ‘The algorithm to plot a graph of the time taken versus n for heap sort is as follows: 1. Initialize an array time_taken to store the time taken to perform heap sort for different values of n. 2. For i in the range 1 to n, do the following: a. Generate a list of i elements. b. Record the start time start_time just before performing heap sort on the list. ¢. Perform heap sort on the list. d. Record the end time end_time just after performing heap sort on the list. €. Calculate the time taken as time_takenfi] = end_time - start_time. 10 3. Plot a graph with non the x-axis and time_taken on the y-axis. This will give you the graph of the time taken versus n for heap sort. Program: def heapSort(arr): len(arr) n for iin range(n, -1, -1): heapify(arr, n, i) for iin range(n-1, 0, -1): arr{iJ, arr{0] = arr{0], arrfi] heapify(arr, i 0) arr =[ 12, 11, 13,5, 6,7] heapSort(arr) n=len(arr) print ("Sorted array is") for iin range(n): print ("%d" 9arrfi]) import timeit import matplotlib.pyplot as plt # list of integers to be sorted list_length = [10000,20000,3 # empty list to store times ee ‘each list time_taken = [] sf # looping through thes for i in range(len(ft length): # code snippet to be executed only once setup_code from heapq import heappush, heappop from random import randint +# code snippet whose execution time is to be measured test_code 1=0) cry Output: HeapSort 2. GRAPH ALGORITHMS: a, Develop a program to implement graph traversal using Breadth First Search from collections import defaultdict Aim: Write a Python program to perform graph traversal using Breadth First Search Algorithm: 1, Create an empty queue and push the starting node onto it. 2. Repeat the following steps until the queue is empty: a, Dequeue a node from the queue and mark it as visited, b. For each unvisited neighbor of the current node, mark it as visited and enqueue it 3. Once the queue is empty, the algorithm is complete. Y Program: Ww class Graph: Oo def __init__(self): & self.graph = defaultdict(list) Qe def addEdge(self, u, v): Y self graph{u] append(v) Ss def BFS(self, start): visited = [False] * le Leow guewe=[] queue-appendsatit) visiealyad= True wl ue: Q{aairt = queue-pop(0) ) for iin self-graphfstart]: print(start, end" if not visited|i: queue.append(i) visitedfi] = True if _name. main_': 2 = Graph) g.addEdge(0, 1) g.addEdge(0, 2) 3B g.addEdge(1, 2) g.addEdge(2, 0) g.addEdge(2, 3) g.addEdge(3, 3) print(’Following is Breadth First Traversal” _" (starting from vertex 2)") g.BFS(2) Output: Following is Breadth First Traversal (starting from vertex 2) 2031 b. Develop a program to implement graph traversal using Depth First Search Program: Aim: Write a Python program to perform graph traversal using depth First Search Algorithm: 1. Create a stack and push the starting node onto it 2. Repeat the following steps until the stack is empty: a. Pop anode from the stack and mark it as visited. b. For each unvisited neighbor of the current node,dpark it as visited and push it onto the stack. Vv Ww 3. Once the stack is empty the algorithm is complet Program: & # define a graph Qe graph = { Y ‘A: [BYCI, Ss B's [D, E}. S ‘C.F, vin wt Es (Fl, mS Feo x } et visit&@Q Set() # Set to keep track of visited nodes. print("The DFS Traversal : Node visited order is") def dfs(visited, graph, node): if node not in visited: # if the node is not visited then visit it and add it to the visited set. print (node) # print the node. visited.add(node) # add the node to the visited set. for neighbour in graph{node]: # for each neighbour of the current node do a recursive call. dis(visited, graph, neighbour) # recursive call. 15 Output: ‘The DFS Traversal : Node visited order is A a mmoe c. Froma given vertex in a weighted connected graph, develop a program tofind the shortest pathsto other vertices using Dijkstra’s algorithm, Aim: Write a Python program to find the shortest paths to other vertices using Dijkstra’s algorithm in a weifgted graph, Algorithm: 1, Create a set $ to keep track of visited vertices, and initialize it with the starting vertex. 2. Create a priority queue Q to keep track of unvisited vertic their distances, and initialize it with the starting vertex and a &(@ance of 0. 3. Repeat the following steps uml Qis empty: SV i. Dequeue the vertex u with the minimunfdiance from Q. ii, AddutoS. L iii, For each neighbor v of u: Qe & iv. If vis already in S, cor v. If the distance to vt ‘wis less than its current distance, update its distance in es 4. Once Q is empty, 3 inces to all vertices have been determined. Program: # define the me vote x na 1), Qn 6,32, HT}, Bi 2, Di 4, E:8), ) E: 3, F: 6}, 3), cH BE (C8, F: (D6) } def dijkstra(graph,start,goal): shortest_distance = {} predecessor = {} unseenNodes = graph 7 infinity = 99999 path = [] for node in unseenNodes: shortest_distance[ node] = infinity shortest_distance[start] = 0 while unseenNodes: minNode = None for node in unseenNodes: if minNode is None: minNode = node elif shortest_distance{node] < shortest itansiminNoa gh minNode = node < ~ if weight + shortest_distance[minNode] < _ C) shortest_distance[ hildNode]: shortest_distance[childNode] = “+ shortest_distance{minNode] predecessor{childNode] = fe for childNode, weight in graph{minNode] items( uunseenNodes.pop(minNode) ~\S currentNode = goal we while curenNode t= pg uy: path.inserr@,cbrrentNode) ro xg es Eror: ‘Qrint(Path not reachable’) break redecessor{currentNode] path.insert(0,start) if shortest_distance{ goal] != infinity: print(‘Shortest distance is '+ str(shortest_distance[ goal])) print(’And the path is ' + str(path)) F) dijkstra(graph, Output: Shortest distance is 10 And the path is ['A’, 'C’, 'B', 'D’, 'F'] 18 d, Find the minimum cost spanning tree of a given undirected graph using Prim’s algorithm, Aim: Write a Python program to Find the minimum cost spanning tree of a given undirected graph using Prim’s algorithm, Algorithm: 1, Create a set V to keep track of visited vertices, and initialize it with an arbitrary starting vertex. iS Create a priority queue Q to keep track of unvisited vertic their distances to V, and initialize it with all vertices adjacent to the vertex, 3. Repeat the following steps until V contains all ver i, Dequeue the vertex u with the minimus i. Addu to V. s iii, For each unvisited neighbor ee iv. If vis already in V, conti v. If the distance to vt! wis less than its current distance in Q, updat. ee nd. 4. Onve V contains all yrs, the minimum cost spaning tee has been constructed. ¢ {0, 3, 0, 0, 7], [6, 8,0, 0, 9], [0, 5, 7, 9, O def minKey(key, mstSet): +# Initialize min value min = float(in?) for v in range(V): if keylv] < min and mstSet{v] == False: min = key[v] 19 min_index = v return min_index def primMST(graph): key = [float(inf)] * V parent = [None] * V key[0] =0 mstSet = [False] * V parent{0] = -1 for cout in range(V): u=minKey(key, mstSet) mstSet[u] = True for v in range(V): < if graphfulfvl > 0 and mstSer{v] — False and keyjs} Yeaph(ullv key[v] = graphfullv] © parent[y] =u & print("Edge \tWeight") & for i in range(1,V): we print(parentfi,"-".i"\t",graphjif arent] 1) = primMST (graph) S Va Output: 1. 3 0-3 6 1-4 5 20 ¢. Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem. Aim: Write a Python program to find all pairs ~ Shortest paths problem using Floyd’s algorithm Algorithm: 1, Create a table of distances between every pair of vertices in G 2. Initialize the shortest path table to be the same as the distance table 3. Fork=0to k-l i. For each pair of vertices (u, v) in G ii. For each vertex w in the set of vertices V xy 62 of the current between u and w and Set the shortest path between u and v to the shortest path and the sum of the shorte; wand. oO 4, Return the shortest path table. & Program: S graph = [[0, 5,9, 7], & SS 40,2, 81, 13,2,0,1), S 16, 5,2, 01] e n= len(graph) S dist = [[Mloat(int Oe in range(n)] for j in range(n)] for iineangagye> for j iprygte(n). an. eraphiifil for k in range(n): for i in range(n): for j in range(n): list{ij] = min(dist{il(j), distLi]{k] + dist{&I{j)) print(dist) Output: {10, 5, 7, 71, (4, 0, 2, 31, [3.2 0, 11.5, 4,2, 0]] a £. Compute the transitive closure of a given directed graph using Warshall's algorithm, Aim: Write a Python program to compute the transitive closure of a directed graph using Warshall’s algorithm Algorithm: 1. Create an adjacency matrix of the graph. Initialize the matrix with the values of the graph. For each vertex v, set the value of the matrix at row v and column v to 1. For each pair of vertices (u,v), if there is an edge from w eSee the value of the matrix at row u and column v to 1. Bey 5. For each triplet of vertices (u, v, w), if the value iatrix at row u and column v is I and the value of the matrix at rowyaind column w is 1, set the value of the matrix at row u and column 6. Repeat step 5 until no more ange transitive closure of the graph. & Program: +#Define the graph graph = { jade. The matrix now contains the } +#Define a function to compute the transitive closure def transitive_closure(graph): #lnitialize the transitive closure matrix with Os closure_matrix = [[0 for j in range(len(graph))] for i in range(len(graph))] #Fill the closure matrix with 1s for direct paths for i in range(len(graph)): for j in grapb[list(graph.keys()lil]: closure_matrix[i)[list(graph. keys()).index(j)] 22 +#Compute the transitive closure using Warshall's algorithm for k in range(len(graph)): for i in range(len(graph)): for j in range(len(graph)): closure_matrix{il[j] = closure_matriafillj] or (closure_matrix{il[&] and closure_matrix{k]{j]) ‘#Print the transitive closure matrix, for row in closure_matrix: print(row) +#Call the function transitive_closure(graph) Output: (0,1, 1,1] (0,0, 1,1] (0,0, 1, 1] (0,0, 1, 11 23 3. ALGORITHM DESIGN TECHNIQUES: a, Develop a program to find out the maximum and minimum numbers in a given list of n numbersusing the divide and conquer technique. Aim: Write a Python program to find out the maximum and minimum numbers of n numbersusing the divide and conquer technique. Algorithm: 1, Divide the list into owo halves. Find the maximum and minimum numbers in each halt. -1 mid = len(arr)//2 L =arr[:mid] R= arr[mid:] merge_sort(L) merge_sort(R) =0 25 while i < len(L) and j < len(R): if Lfi] pivot] retun sort(left) + middle + quick_sort(tight) # Gerfsgate an array of random numbers arr =[5, 6,7, 8, 1, 2, 12, 14] # Caleulate the time taken to sort the array start time.time() sorted_arr = quick_sort(arr) end = time.time() # Print the sorted array print("Sorted array: orted_arr) # Calculate and print the time taken to sort the array end - start, "seconds") 28 # Plot a graph of the time taken versus n n_values = [10, 100, 1000, 10000) time_values = [] for n in n_values: arr = [i for i in range(n)] start = time.time() sorted_arr = quick_sort(arr) end = time.time() time_values.append(end - start) pit.plot(n_values, time_values) ) plt.ylabel(’Time taken") pit.xlabel( plt-title("Quicksort") plt.show() Output: Quicksort ‘6000 8000 10000 29 4, STATE SPACE SEARCH ALGORITHMS: a, Implement N Queens problem using Backtracking. Aim: Write a Python program to solve N- Queens problem using backtracking. Algorithm: // Create an empty array of size n / Create a function to check if a queen can be placed in a given row and column 1/ Create a function to place a queen in a given row and column // Create a function to remove a queen froma given row andplumn 1 Create a function to solve the n queens problem using oRecking / Function to check if a queen can be placed in a gepYow and column obi ( in the same row func canPlaceQueen(row, col int, board [] 1/ Check if any other queen is for i:= 0; i = 0 && j > =i jl { if boardlil{j] = return false » 3 for row, col; i = 0; i, if boardfil{j] = 1 { return false , 4 return true } 30 / Function to place a queen in a given row and column fune placeQueen(row, col int, board( II] int) { board{row[col] = 1) 1 Function to remove a queen from a given row and column func removeQueen(row, col int, board[][] int) { board[row][col] = 0 } 1 Function to solve the n queens problem using backtracking func solveNQueens(board{][] int) bool { if len(board) == 0 { return true} fori 0; i < len(board); i++ { oO for j = 0; = len(board): return True # iterate through all for i in range(len sardfi}[col] = 1 # recur to place rest of the queens if solve_n_queens(board, col + 1) == True: return True # backtrack board[i}{co!] = 0 return False # driver code if __name__=="__main_" # size of board 32 Output: n= int(input(""Enter the size of board: ")) # create an empty board board = [[0 for j in range(n)] for i in range(n)] \_queens(board, 0) == False: print("Solution does not exist") if solve. else: print_board(board) Enter the size of board: 4 oo10 1000 ooo 0100 33 5. APPROXIMATION ALGORITHMS RANDOMIZED ALGORITHMS: a. 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 Aim: Write a Python program to find the optimal solution for the Travelling Salesperson problem using approximation algorithm and determine the error in the approximation Algorith Ww 1. Initialize the solution with the first city as the startifg point. 2. Calculate the distance from the current city tg abhother citi 3. Select the nearest city from the current ci mark it as visited. Calculate the total distance ~ & Repeat steps 2-4 until all een visited. ies Calculate the total distance led. Compare the total dstangsiréelled with the optimal solution. erase If the total distance led is less than the optimal solution, then the current solution is the appa 9. Ithe totaaagince travelled is more than the optimal solution, then repeat steps 2- 7 using Yerent starting city g ‘imate solution. Program: #importing libraries import numpy as np import math #defining the distance matrix dist_matrix = np.array({[0, 10, 15, 20], [10, 0, 35, 25), [15, 35, 0, 30), [20, 25, 20, 01) 34 ‘#defining the cost matrix cost_matrix = np.array({{0, 10, 15, 20}, [10, 0, 35, 25], [15, 35, 0, 30), [20, 25, 20, 01) #defining the number of cities num =4 #defining the optimal solution function def opt_solution(dist_matrix, cost_matrix, num_cities): initializing the cost matrix cost_matr np.zeros((num_cities, num_cities)) initializing the visited array visited = [False] * num_cities #initializing the current city current _city = 0 #initializing the total cost total_cost = #looping through the cigs, 1: for iin range(num, inating ie din_eost ninco int #injeigfing the next_city RCcity=0 #looping through the cities for j in range(num_cities): fchecking if the city has been visited if visited{j] == False: #checking if the cost is less than min_cost if cost_matrix{current_city][j] < min_cost: #updating the min_cost min_cost = cost_matrix[eurrent_city]{j] #updating the next_city 35 next_city = j ‘updating the total cost total_cost += min_cost ‘#updating the visited array visited{next_city] = True updating the current city current_city = next_ returning the total cost return total_cost #calculating the optimal solution opt_sol = opt_solution(dist_matrix, cost_matrix, cum ete 7 VY +#printing the optimal solution. print("Optimal Solutio : ", opt_sol) #defining the approximation algorithm Oo def approx_algorithm(dist_matrix, age men #initializing the cost matrix eS ‘cost_matrix = np.zeros((num_¢j Sin cites) i ializing the visited arr visited = [False] * num, initializing the cugrgit Sity current_city = Wining ge total cost total_gase= 0 visi Rronseck =True for iin range(num_cities - 1): #initializing the min_cost math.int Hinitializing the next_city next_city = 0 #looping through the cities for j in range(num_cities): if visited{j] if dist_matrix{current_city][j] < min_cost: False: 36 #updating the min_cost min_cost = dist_matrix{current_city][j] #updating the next next_city = j total cost += min_cost #updating the visited a visited{next_city] = True #updating the current city current_city = next_city #returning the total cost return total_cost approx_sol = approx_algorithm(dist_matrix, cost printing the approximated solution print"Approximated Solution: ", approx_sol) alculating the error error opt_sol - approx_sol printing the error error) print("Error: " Output: 37 b Implement randomized algorithms for finding the k"" smallest number. Aim: Write a Python program to find the kth smallest number using randomized algorithm Algorithm: 1. Create an array of size n, where n is the number of elements in the array. 2. Randomly select an element from the array and store it in a variable. 3. Compare the randomly selected element with the kth smallest element. 4. If the randomly selected element is smaller than the kth smallest element, then replace the kth smallest element with the randomly selected glement. 5. Repeat steps 2-4 until the kth smallest element is found. Program: import random def kthSmallest(arr, k): n= len(arr) temp = arrf:k] contain for xe e range(k): RY if arr{i] < temp[j|: x templil = arti ee break return temp[k - 1] # Driver Code arr = [12, 3, 5,7, 19] k=2 print("K'th smallest element is", kthSmallest(arr, k)) Output: K'th smallest element is 5 38

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