为什么向binary_search
函数传递一个空列表?毕竟,它并不是真正的空。
from typing import List
def binary_search(nums: List[int], item: int):
print("binary_search nums", nums)
low = 0
high = len(nums) - 1
while low <= high:
middle = (low + high) // 2
if nums[middle] == item:
return middle
if nums[middle] > item:
high = middle - 1
if nums[middle] < item:
low = middle + 1
return None
def smallest_find(nums: List[int]):
smallest = nums[0]
smallest_index = 0
for i in range(1, len(nums)):
if nums[i] < smallest:
smallest = nums[i]
smallest_index = i
return smallest_index
def selection_sort(nums: List[int]):
sorted_nums = []
for _ in range(len(nums)):
smallest_index = smallest_find(nums)
sorted_nums.append(nums.pop(smallest_index))
return sorted_nums
import random
while True:
nums = [random.randint(-100, 100) for _ in range(20)]
item = 24
if item in nums:
print(nums)
print(selection_sort(nums))
print(binary_search(selection_sort(nums), item))
break
结果:
[20, 84, -65, -76, -46, -7, 19, 48, -55, 31, 62, -86, 16, 24, 67, -87, -65, -57, 12, 61]
[-87, -86, -76, -65, -65, -57, -55, -46, -7, 12, 16, 19, 20, 24, 31, 48, 61, 62, 67, 84]
binary_search nums []
None
为什么向binary_search
函数传递一个空列表?毕竟,它并不是真正的空。
Python 3.8.10