常用排序算法的Python实现汇总
之前总结了一篇C++实现各排序算法的文章:
现改用Python实现。程序源文件可以在我的GitHub下载得到。
堆排序
import math
def buildMaxHeap(arr):
for i in range(math.floor(len(arr)/2),-1,-1):
heapify(arr,i)
def heapify(arr, i):
left = 2*i+1
right = 2*i+2
largest = i
if left < arrLen and arr[left] > arr[largest]:
largest = left
if right < arrLen and arr[right] > arr[largest]:
largest = right
if largest != i:
swap(arr, i, largest)
heapify(arr, largest)
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def heapSort(arr):
global arrLen
arrLen = len(arr)
buildMaxHeap(arr)
for i in range(len(arr)-1,0,-1):
swap(arr,0,i)
arrLen -=1
heapify(arr, 0)
return arr
def main():
arr1 = [6, 4, 3, 7, 5, 1, 2]
print(arr1)
arr = heapSort(arr1)
print(arr)
if __name__ == "__main__":
main()
归并排序
import math
def mergesort(arr):
if(len(arr) < 2 ):
return arr
middle = math.floor(len(arr)/2)
left, right = arr[0:middle], arr[middle:]
return merge(mergesort(left), mergesort(right))
def merge(left, right):
result = []
while left and right:
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
while left:
result.append(left.pop(0))
while right:
result.append(right.pop(0))
return result
def main():
arr1 = [6, 4, 3, 7, 5, 1, 2]
print(arr1)
arr = mergesort(arr1)
print(arr)
if __name__ == "__main__":
main()
快速排序
def quickSort(arr, left=None, right=None):
left = 0 if not isinstance(left,(int, float)) else left
right = len(arr)-1 if not isinstance(right, (int, float)) else right
if left < right:
partitionIndex = partition(arr, left, right)
quickSort(arr, left, partitionIndex-1)
quickSort(arr, partitionIndex+1, right)
return arr
def partition(arr, left, right):
pivot = left
index = pivot + 1
i = index
while i <= right:
if arr[i] < arr[pivot]:
swap(arr, i, index)
index += 1
i += 1
swap(arr, pivot, index - 1)
return index - 1
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def main():
arr1 = [6, 4, 3, 7, 5, 1, 2]
print(arr1)
arr = quickSort(arr1)
print(arr)
if __name__ == "__main__":
main()