# -*- coding: utf-8 -*- # ------------------------------------------------------------------ # File Name: binary_search_test.py # Author: https://xlindo.com/kewenlu # Version: ver0_1 # Created: 2021/12/29 # Description: To test the time complexity for the binary search # algorithm. # License: GPLv3 # ------------------------------------------------------------------
import matplotlib.pyplot as plt import random import time
defbinary_search_right(arr, t): """binary search algorithm Args: arr (list): list to be searched t (int): target number Returns: int: index for the target. If not exists, -1 """ l, r = 0, len(arr) - 1 while l <= r: m = round(l + (r - l) / 2) # rounding if arr[m] < t: l = m + 1# adjust the searching range to the right section elif arr[m] > t: r = m - 1# adjust the searching range to the left section else: return m # found return -1# not found
deftime_counter(n, n_tests): """To test the average running time for the search Args: n (int): array to be searched n_tests (int): repeated times for searching Returns: int: the average elapsed time """ arr = [] for i inrange(n): arr.append(i)
# let searching target randomly arr_rand = [i for i inrange(n)] random.shuffle(arr_rand)
start_time = time.time() for n_test inrange(n_tests): for i in arr_rand: assert(binary_search_right(arr, i) == arr[i]) duration_time = time.time() - start_time print("array length (n): %d, n_tests: %d, duration_time: %lf" % (n, n_tests, duration_time / n)) return duration_time / n
# test and plot the result arr_n = [100 * 2 ** n for n inrange(11)] # 100, 1 000, ... for array size time_cnt = [time_counter(100 * 2 ** n, 1000) for n inrange(11)] # 1 000 times searching
arr_idx = [n for n inrange(11)]
plt.title("The time that increases linearly with the length\nof the array increases exponentially") plt.xlabel("Array size (100*2^n)") plt.ylabel("Average elapsed time") plt.plot(arr_idx, time_cnt) plt.scatter(arr_idx, time_cnt)