常见算法汇总
Posted jeffrey-yang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常见算法汇总相关的知识,希望对你有一定的参考价值。
binary search
def binary_search(arr, item):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
guess = arr[mid]
if item == guess:
return mid
if item < guess:
high = mid - 1
else:
low = mid + 1
return None
selection sort
def find_smallest(arr):
smaller = arr[0]
smaller_index = 0
for i in range(1, len(arr)):
if arr[i] < smaller:
smaller = arr[i]
smaller_index = i
return smaller_index
def selection_sort(arr):
sorted_arr = []
while arr:
smaller_index = find_smallest(arr)
sorted_arr.append(arr.pop(smaller_index))
return sorted_arr
以上是关于常见算法汇总的主要内容,如果未能解决你的问题,请参考以下文章