快排:先分在排
def quickSort(arr, left, right):
if left < right:
partitionIndex = partition(arr, left, right)
quickSort(arr, left, partitionIndex - 1)
quickSort(arr, partitionIndex + 1, right)
return
def partition(arr, left, right):
i, j = left, right
pivot = arr[left]
while i < j:
while i < j and arr[j] >= pivot:
j -= 1
while i < j and arr[i] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[j], arr[left] = arr[left], arr[j]
return j
arr = [3,1,2,4,6,5]
quickSort(arr, 0, len(arr)-1)
归并:排好再合起来
def mergeSort(arr):
if len(arr) < 2: return arr
mid = len(arr) // 2
left = mergeSort(arr[:mid])
right = mergeSort(arr[mid:])
return merge(left, right)
def merge(left, right):
res = []
while left and right:
if left[0] < right[0]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
while left:
res.append(left.pop(0))
while right:
res.append(right.pop(0))
return res
arr = [3,1,2,4,6,5]
a = mergeSort(arr)
二分:
def binarySearch(arr, tar):
left, right = 0, len(arr)-1
while left <= right:
mid = (left + right) // 2
if tar > arr[mid]:
left = mid + 1
elif tar == arr[mid]:
return mid
else:
right = mid - 1
return -1
arr = [1,2,3,4,5]
a = binarySearch(arr, 6)