Linear vs Binary Search
線性搜尋 vs. 二分搜尋
Linear Search
def linear_search(list, key):
"""If key is in the list returns its position in the list,
otherwise returns -1."""
for i, item in enumerate(list):
if item == key:
return i
return -1
Binary Search
def binary_search(list, key):
"""Returns the position of key in the list if found, -1 otherwise.
List must be sorted.
"""
# Sort the List
list.sort()
left = 0
right = len(list) - 1
while left <= right:
middle = (left + right) // 2
if list[middle] == key:
return middle
if list[middle] > key:
right = middle - 1
if list[middle] < key:
left = middle + 1
return -1