冒泡排序
冒泡排序顾名思义,大的泡泡先升起来,排在最后,即先将最后的元素选出来。
def BubbleSort(arr):
for i in range(len(arr):
for j in range(len(arr) - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
选择排序
不同于冒泡从后向前进行排序,选择排序则为从前向后,选定最小的第n个元素,放在第n个位置。
def SelectionSort(arr):
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[j] > arr[i]:
arr[j], arr[i] = arr[i], arr[j]
return arr
归并排序
def MergeSort(arr):
if len(arr) <= 1:
return arr
pi = len(arr) // 2
left_arr = MergeSort(arr[:pi]}
right_arr = MergeSort(arr[pi:])
Merge(left_arr, right_arr)
def Merge(left_arr, right_arr):
left, right = 0, 0
res = []
while left < len(left_arr) and right < len(right_arr):
if left_arr[left] > right_arr[right]:
res.append(left_arr[left])
left += 1
else:
res.append(right_arr[right])
right += 1
res.append(list(left_arr[left:]))
res.append(list(right_arr[right:]))
return res
快速排序
def Partition(arr, low, high):
left, right = low, high
pivot = arr[low]
while left < right:
while left < right and arr[right] >= pivot:
right -= 1
while left < right and arr[left] <= pivot:
left += 1
arr[left], arr[right] = arr[right], arr[left]
arr[left], arr[low] = arr[low], arr[left]
return left
def QuickSort(arr, low, high):
if low >= high:
return arr
pi = Partition(arr, low, high)
QuickSort(arr, low, pi - 1)
QuickSort(arr, pi + 1, high)
return arr
堆排序
#构造大堆顶
def BigHeap(arr, start, end):
root = start
while True:
child = root * 2 + 1
if child > end:
break
if child + 1 <= end and arr[child] < arr[child + 1]:
child += 1
if arr[root] < arr[child]:
arr[root], arr[child] = arr[child] , arr[root]
root = child
else:
break
def HeapSort(arr):
first = len(arr) // 2 - 1
for i in range(first, -1, -1):
BigHeap(arr, first, len(arr) - 1)
for j in range(len(arr) - 1, 0, -1):
arr[0], arr[j] = arr[j], arr[0]
BigHeap(arr, 0, j - 1)
return arr