Python 八大排序算法速度比较

Python 八大排序算法速度比较

这篇文章并不是介绍排序算法原理的,纯粹是想比较一下各种排序算法在真实场景下的运行速度。

算法由 Python 实现,用到了一些语法糖,可能会和其他语言有些区别,仅当参考就好。

测试的数据是自动生成的,以数组形式保存到文件中,保证数据源的一致性。

排序算法

image

直接插入排序

  • 时间复杂度:O(n²)
  • 空间复杂度:O(1)
  • 稳定性:稳定

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">def insert_sort(array): for i in range(len(array)): for j in range(i): if array[i] < array[j]:
array.insert(j, array.pop(i)) break
return array</pre>

希尔排序

  • 时间复杂度:O(n)
  • 空间复杂度:O(n√n)
  • 稳定性:不稳定

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">def shell_sort(array):
gap = len(array) while gap > 1:
gap = gap // 2
for i in range(gap, len(array)): for j in range(i % gap, i, gap): if array[i] < array[j]:
array[i], array[j] = array[j], array[i] return array</pre>

简单选择排序

  • 时间复杂度:O(n²)
  • 空间复杂度:O(1)
  • 稳定性:不稳定

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">def select_sort(array): for i in range(len(array)):
x = i # min index
for j in range(i, len(array)): if array[j] < array[x]:
x = j
array[i], array[x] = array[x], array[i] return array</pre>

堆排序

  • 时间复杂度:O(nlog₂n)
  • 空间复杂度:O(1)
  • 稳定性:不稳定

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">def heap_sort(array): def heap_adjust(parent):
child = 2 * parent + 1 # left child
while child < len(heap): if child + 1 < len(heap): if heap[child + 1] > heap[child]:
child += 1 # right child
if heap[parent] >= heap[child]: break heap[parent], heap[child] =
heap[child], heap[parent]
parent, child = child, 2 * child + 1 heap, array = array.copy(), [] for i in range(len(heap) // 2, -1, -1):
heap_adjust(i) while len(heap) != 0:
heap[0], heap[-1] = heap[-1], heap[0]
array.insert(0, heap.pop())
heap_adjust(0) return array</pre>

冒泡排序

  • 时间复杂度:O(n²)
  • 空间复杂度:O(1)
  • 稳定性:稳定

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">def bubble_sort(array): for i in range(len(array)): for j in range(i, len(array)): if array[i] > array[j]:
array[i], array[j] = array[j], array[i] return array</pre>

快速排序

  • 时间复杂度:O(nlog₂n)
  • 空间复杂度:O(nlog₂n)
  • 稳定性:不稳定

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">def quick_sort(array): def recursive(begin, end): if begin > end: return l, r = begin, end
pivot = array[l] while l < r: while l < r and array[r] > pivot:
r -= 1
while l < r and array[l] <= pivot:
l += 1 array[l], array[r] = array[r], array[l]
array[l], array[begin] = pivot, array[l]
recursive(begin, l - 1)
recursive(r + 1, end)

recursive(0, len(array) - 1) return array</pre>

归并排序

  • 时间复杂度:O(nlog₂n)
  • 空间复杂度:O(1)
  • 稳定性:稳定

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">def merge_sort(array): def merge_arr(arr_l, arr_r):
array = [] while len(arr_l) and len(arr_r): if arr_l[0] <= arr_r[0]:
array.append(arr_l.pop(0)) elif arr_l[0] > arr_r[0]:
array.append(arr_r.pop(0)) if len(arr_l) != 0:
array += arr_l elif len(arr_r) != 0:
array += arr_r return array def recursive(array): if len(array) == 1: return array
mid = len(array) // 2 arr_l = recursive(array[:mid])
arr_r = recursive(array[mid:]) return merge_arr(arr_l, arr_r) return recursive(array)</pre>

基数排序

  • 时间复杂度:O(d(r+n))
  • 空间复杂度:O(rd+n)
  • 稳定性:稳定

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">def radix_sort(array):
bucket, digit = [[]], 0 while len(bucket[0]) != len(array):
bucket = [[], [], [], [], [], [], [], [], [], []] for i in range(len(array)):
num = (array[i] // 10 ** digit) % 10 bucket[num].append(array[i])
array.clear() for i in range(len(bucket)):
array += bucket[i]
digit += 1
return array</pre>

速度比较

image

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">from random import random from json import dumps, loads # 生成随机数文件
def dump_random_array(file='numbers.json', size=10 ** 4):
fo = open(file, 'w', 1024)
numlst = list() for i in range(size):
numlst.append(int(random() * 10 ** 10))
fo.write(dumps(numlst))
fo.close() # 加载随机数列表
def load_random_array(file='numbers.json'):
fo = open(file, 'r', 1024) try:
numlst = fo.read() finally:
fo.close() return loads(numlst)</pre>

image

显示执行时间

如果数据量特别大,采用分治算法的快速排序和归并排序,可能会出现递归层次超出限制的错误。

解决办法:导入 sys 模块(import sys),设置最大递归次数(sys.setrecursionlimit(10 ** 8))。

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Source Code Pro", Consolas, Menlo, Monaco, "Courier New", monospace !important; font-size: 0.8rem !important; background: none !important; line-height: 1.2rem !important;">@exectime def bubble_sort(array): for i in range(len(array)): for j in range(i, len(array)): if array[i] > array[j]:
array[i], array[j] = array[j], array[i] return array

array = load_random_array() print(bubble_sort(array) == sorted(array))</pre>

↑ 示例:测试直接插入排序算法的运行时间,@exectime 为执行时间装饰器。

算法执行时间

image

算法速度比较

image
image
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,651评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,468评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,931评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,218评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,234评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,198评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,084评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,926评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,341评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,563评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,731评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,430评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,036评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,676评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,829评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,743评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,629评论 2 354

推荐阅读更多精彩内容