defmerge_sort(a: List[int]):
_merge_sort_between(a,0,len(a)-1)def_merge_sort_between(a: List[int], low:int, high:int):# The indices are inclusive for both low and high.if low < high:
mid = low +(high - low)//2
_merge_sort_between(a, low, mid)
_merge_sort_between(a, mid +1, high)
_merge(a, low, mid, high)def_merge(a: List[int], low:int, mid:int, high:int):# a[low:mid], a[mid+1, high] are sorted.
i, j = low, mid +1
tmp =[]while i <= mid and j <= high:if a[i]<= a[j]:
tmp.append(a[i])
i +=1else:
tmp.append(a[j])
j +=1
start = i if i <= mid else j
end = mid if i <= mid else high
tmp.extend(a[start:end +1])
a[low:high +1]= tmp
快速排序
defquick_sort(a: List[int]):
_quick_sort_between(a,0,len(a)-1)def_quick_sort_between(a: List[int], low:int, high:int):if low < high:# get a random position as the pivot
k = random.randint(low, high)
a[low], a[k]= a[k], a[low]
m = _partition(a, low, high)# a[m] is in final position
_quick_sort_between(a, low, m -1)
_quick_sort_between(a, m +1, high)def_partition(a: List[int], low:int, high:int):
pivot, j = a[low], low
for i inrange(low +1, high +1):if a[i]<= pivot:
j +=1
a[j], a[i]= a[i], a[j]# swap
a[low], a[j]= a[j], a[low]return j
插入排序
definsertion_sort(a: List[int]):
length =len(a)if length <=1:returnfor i inrange(1, length):
value = a[i]
j = i -1while j >=0and a[j]> value:
a[j +1]= a[j]
j -=1
a[j +1]= value
冒泡排序
from typing import List
defbubble_sort(a: List[int]):
length =len(a)if length <=1:returnfor i inrange(length):
made_swap =Falsefor j inrange(length - i -1):if a[j]> a[j +1]:
a[j], a[j +1]= a[j +1], a[j]
made_swap =Trueifnot made_swap:break
defbsearch(nums: List[int], target:int)->int:"""Binary search of a target in a sorted array
without duplicates. If such a target does not exist,
return -1, othewise, return its index.
"""
low, high =0,len(nums)-1while low <= high:
mid = low +(high - low)//2if nums[mid]== target:return mid
elif nums[mid]< target:
low = mid +1else:
high = mid -1return-1