关联文档:5种Python排序算法性能比较
本文介绍:快速排序、堆排序、计数排序
快速排序 Python 编写:
def _internal_qsort(arr, start, end):
if (end - start < 2):
return
if (end - start == 2):
if (arr[start] > arr[start + 1]):
arr[start], arr[start + 1] = arr[start + 1], arr[start]
return
l = start
r = end - 1
balance = (arr[l] + arr[r] + arr[random.randint(l, r)]) / 3
# print(arr,start,end,balance)
while(True):
while(arr[l] < balance) : l += 1
while(arr[r] > balance) : r -= 1
if (l >= r):
break
arr[l], arr[r] = arr[r], arr[l]
l += 1
r -= 1
_internal_qsort(arr, start, l)
_internal_qsort(arr, r + 1, end)
def qsort(arr):
_internal_qsort(arr, 0, len(arr))
堆排序 Python 编写:
def _internal_heapify(arr, n, i):
if (n <= 1):
return
while (True):
i1 = i * 2 + 1
i2 = i * 2 + 2
maxi = i
if (i1 < n and arr[i1] > arr[maxi]): maxi = i1
if (i2 < n and arr[i2] > arr[maxi]): maxi = i2
# 如果不需要交换,堆化提前完成
if (maxi == i):
break
arr[i], arr[maxi] = arr[maxi], arr[i]
i = maxi
def heapsort(arr):
n = len(arr)
if (n <= 1):
return
# step 1 建堆
# 设最后一个叶子节点的索引是 x
# x * 2 + 1 < n
# x < (n - 1) / 2
for i in range((n - 1) // 2, -1, -1):
_internal_heapify(arr, n, i)
# step 2 依次取根节点,得到有序数组,取 (n-1) 次
for i in range(n - 1):
j = n - i - 1
arr[0], arr[j] = arr[j], arr[0]
_internal_heapify(arr, n - i - 1, 0)
计数排序 Python 编写:
def countingsort(arr):
nmax, nmin = arr[0], arr[0]
for i in range(1, len(arr)):
if (arr[i] > nmax): nmax = arr[i]
if (arr[i] < nmin): nmin = arr[i]
countings = [0] * (nmax - nmin + 1)
for i in range(len(arr)):
countings[arr[i] - nmin] += 1
i = 0
for c in range(len(countings)):
for j in range(countings[c]):
arr[i] = c + nmin
i += 1