# 经典算法摘录

``````# 二分查找 -- 适用于`有序`元素列表
def binary_search(array, item):
print("二分查找开始 O(log n)")
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high)
guess = array[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None

# 选择排序
def selection_sort(arr):
print("选择排序 O(n2)")
newArr = []
for i in range(len(arr)):
smallest = find_smallest(arr)
newArr.append(arr.pop(smallest))
return newArr

# 查找数组最小元素
def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index

# 快速排序
def quicksort(array):
print("快速排序 O(n log n)")
if len(array) < 2:
return array
else:
pivot = array[0]
less = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)

if __name__ == '__main__':
# print(quicksort([10, 5, 2, 3]))
# print(binary_search([2, 3, 5, 10], 10))
print(selection_sort([5, 3, 6, 2, 10]))
``````