二分查找
二分查找的複雜度爲O(nlogn)
,使用二分查找的前提是該序列爲一個有序數列。
def binary_search(arr, item):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
guess = list[mid]
if guess == item:
return guess
elif guess > item:
high = mid - 1
else:
low = low + 1
return None
選擇排序
選擇排序的複雜度爲O()。
# method 1
def findSmallest(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 SelectionSort(arr):
new_arr = []
for i in range(len(arr)):
smallest = findSmallest(arr)
new_arr.append(arr.pop(smallest))
return new_arr
# method 2
new_arr = sorted(arr)
快速排序
快速排序的複雜度爲O(nlogn)
def quickSort(arr):
if len(arr) < 2:
return arr
else:
pivot = arr[0]
less = [i for i in arr[1:] if i <= pivot]
greater = [i for i in arr[1:] if i > pivot]
return quickSort(less) + [pivot] + quickSort(greater)
遞歸求和
def sum(list):
if list == []:
return 0
else:
return list[0] + sum(list[1:])