Question
PYTHON CODE My code gives me error if n 1e6/1e8 and m = 1000 CODE BELOW: import random import time # Function to perform linear
PYTHON CODE
My code gives me error if n 1e6/1e8 and m = 1000
CODE BELOW:
import random
import time
# Function to perform linear search
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return True
return False
# Function to perform binary search
def binary_search(arr, x):
left = 0
right = len(arr) - 1
while left
mid = (left + right) // 2
if arr[mid] == x:
return True
elif arr[mid]
left = mid + 1
else:
right = mid - 1
return False
# Generate n random integers and sort them
n = 1e6
range_start = 1
range_end = float(100)
arr = sorted(random.uniform(range(range_start, range_end), n))
# Generate m random numbers and perform linear and binary search on the array
m = 1000
search_times = []
for i in range(m):
# Generate a random number to search for
x = random.unifrom(range_start, range_end)
# Perform linear search and record the time taken
start_time = time.time()
linear_search(arr, x)
end_time = time.time()
linear_time = end_time - start_time
# Perform binary search and record the time taken
start_time = time.time()
binary_search(arr, x)
end_time = time.time()
binary_time = end_time - start_time
# Record the search times
search_times.append((linear_time, binary_time))
# Calculate the average search times and number of times the number was found
linear_sum = 0
binary_sum = 0
num_found = 0
for linear_time, binary_time in search_times:
linear_sum += linear_time
binary_sum += binary_time
if linear_time == 0:
num_found += 1
avg_linear_time = linear_sum / m
avg_binary_time = binary_sum / m
# Print the results
print(f"Average linear search time: {avg_linear_time:.6f}")
print(f"Average binary search time: {avg_binary_time:.6f}")
print(f"Number of times the number was found: {num_found}")
\begin{tabular}{|l|l|l|l|l|} \hline Data size (n) & searchentries(m) & \# of found & Averagetimespentlinearsearch & Averagetimespentbinarysearch \\ \hline 100 & 50 & & & \\ \hline 10,000 & 1000 & & & \\ \hline 1e6 & 1000 & & & \\ \hline 1e8 & 1000 & & & \\ \hline \end{tabular}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started