Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

LAB_3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Assignment Number: 3

NAME: Md. Muaz Sayyed ROLLNO: 60


CLASS: TY-IT-A BATCH: 3
___________________________________________________________________
Problem Statement:
1. Binary Search analysis code
2. Make a table of n and execution time and graph of it.
3. Determine time complexity of binary search using substitution approach for
best case and worst case.
Answer:
Pseudo Code:
BS(a, i, j, x)
{ mid=(i+j)/2;
if (a[mid]==x)
return mid;
Else
if (a[mid]>x)
BS(a,i,mid-1,x);
else
BS(a,mid+1,j,x);
}
Code:

import time
import matplotlib.pyplot as plt
import numpy as np

def binary_search(arr, target):


low, high = 0, len(arr) - 1

while low <= high:


mid = (low + high) // 2
mid_value = arr[mid]
if mid_value == target:
return mid
elif mid_value < target:
low = mid + 1
else:
high = mid - 1

return -1 # If the target is not found in the array

def generate_binary_search_plot(start_n, end_n, target):


data = []

print("n\tExecution Time (seconds)")


print("---------------------------")

for n in range(start_n, end_n):


arr = np.arange(n)

start_time = time.perf_counter()
binary_search(arr, target)
end_time = time.perf_counter()

execution_time = (end_time - start_time)

data.append((n, execution_time))

print(f"{n}\t {execution_time:.6f}")

# Generate plot
n_values, time_values = zip(*data)

plt.figure(figsize=(7, 5))
# Plot for n vs execution time
plt.plot(n_values, time_values, label='Execution Time')
plt.title('n vs Execution Time (Binary Search)')
plt.xlabel('n')
plt.ylabel('Execution Time (seconds)')
plt.legend()

plt.show()

# Set the range for n


start_n_binary_search = 10000
end_n_binary_search = 10100

# Set the target value for binary search


target_value = np.random.randint(start_n_binary_search,
end_n_binary_search)

# Generate plot for Binary Search


generate_binary_search_plot(start_n_binary_search,
end_n_binary_search, target_value)

Output:
Time Complexity of Binary Search using Substitution Method:

{()
1 ,∧n=1
T (n)=
T
n
2
T
+c ,∧n>1 2
n
() n
that the a problem of ¿is divided into problem of ¿( ¿ ) each .
2

c is constant ti signifiesme needed for comparison and computing mid can be taken as 1

{()
1,∧n=1
T (n)=
T
n
2
+1 ,∧n>1
T ( n )=T
n
2 ()
+1Using substitution method T ( n )= T
n
4 (() )
+1 +1

( 8 )
(
T ( n )= T
n
)+ 1 +1T ( n )=T ( )+32 =n ,thus k =lo g n
n
8
k

T (n)=k + T
( )
n
2
k ()
ma x value of k can be lo g nT (n)=lo g n+ T
n
n
T (n)=logn+ T ( 1 )T (n)=lo g n

Time complexity of binarch search isO ( log n ) .

You might also like