1、二分查找
def search(nums, target):
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) // 2
base = nums[mid]
if target == base:
return mid
elif target < base:
r = mid - 1
else:
l = mid + 1
return -1
2、快速排序
nums = [3,2,7,8,6,4,1,5,7,8,6,4,7,8,6,4,7,8,6,4,]
# 方式1
def qulick_click(arr):
l = len(arr)
if l <= 1:
return arr
base = arr[0]
arr_left = [i for i in arr[1:] if i < base]
arr_right = [i for i in arr[1:] if i >= base]
return qulick_click(arr_left) + [base] + qulick_click(arr_right)
#方式2 时间优化
# 快速排序
def partition(li,left,right):
tmp = li[left]
while left < right:
while left < right and li[right] >= tmp: #从右边找比tmp小的数
right -= 1 #继续从右往左查找
li[left] = li[right] #把右边的值写到左边空位上
while left < right and li[left] <= tmp:
left += 1
li[right] = li[left] #把左边的值写到右边空位上
li[left] = tmp #把tmp归位
return left
def quick_sort(li,left,right):
if left < right :#至少两个元素
mid = partition(li,left,right)
quick_sort(li,left,mid-1)
quick_sort(li,mid+1,right)
li = [5,7,4,6,3,1,2,9,8]
quick_sort(li,0,len(li)-1)
print(li)
3、归并排序
#merge的功能是将前后相邻的两个有序表归并为一个有序表的算法。
def merge(left, right):
ll, rr = 0, 0
result = []
while ll < len(left) and rr < len(right):
if left[ll] < right[rr]:
result.append(left[ll])
ll += 1
else:
result.append(right[rr])
rr += 1
result+=left[ll:]
result+=right[rr:]
return result
def merge_sort(alist):
if len(alist) <= 1:
return alist
num = len(alist) // 2 # 从中间划分两个子序列
left = merge_sort(alist[:num]) # 对左侧子序列进行递归排序
right = merge_sort(alist[num:]) # 对右侧子序列进行递归排序
return merge(left, right) #归并
tesl=[1,3,45,23,23,12,43,45,33,21]
print(merge_sort(tesl))
#[1, 3, 12, 21, 23, 23, 33, 43, 45, 45]