# Python天天美味(30) - python数据结构与算法之快速排序

### 1. 快速排序

def quicksort(data, low = 0, high = None):
if high == None:
high = len(data) - 1
if low < high:
s, i, j = data[low], low, high
while i < j:
while i < j and data[j] >= s:
j = j - 1
if i < j:
data[i] = data[j]
i = i + 1
while i < j and data[i] <= s:
i = i + 1
if i < j:
data[j] = data[i]
j = j - 1
data[i] = s
quicksort(data, low, i - 1)
quicksort(data, i + 1, high)

### 2. 冒泡排序

def bubblesort(data):
for i in range(len(data) - 1, 0, -1):
for j in range(0, i):
if data[j] > data[j + 1]:
data[j], data[j + 1] = data[j + 1], data[j]

### 3. 性能比较

import random
import datetime
import copy

def sort_perfmon(sortfunc, data):
sort_data = copy.deepcopy(data)
t1 = datetime.datetime.now()
sortfunc(sort_data)
t2 = datetime.datetime.now()
print sortfunc.__name__, t2 - t1
#print sort_data

data = [random.randint(0, 65536) for i in range(2000)]
#print data
sort_perfmon(quicksort, data)
sort_perfmon(bubblesort, data)

### 4. 结果

quicksort 0:00:00.062000
bubblesort 0:00:03.563000

5. 代码下载

#### Python 天天美味系列（总）

...

posted @ 2008-09-20 22:05 CoderZh 阅读(...) 评论(...) 编辑 收藏