您的位置:首页 > 编程语言 > Python开发

python算法--快速排序详细实现

2013-05-06 10:03 429 查看
快速排序的基本思想就是:分割。即以序列中的一个关键字(第一个,或者最后一个,或者任意一个)作为枢轴,将整个序列分割成两部分----比枢轴大的一部分和比枢轴小的一部分。然后再分别对这两部分(不包括枢轴)进行递归运算,直到序列有序。

如何划分?

令序列中第一个元素的下标为first,最后一个为last,枢轴为pivot, 序列为array。 这样从两端开始,让 array[first] 和 array[last] 分别交替和 array[pivot] 作比较。如果first(或者last)和pivot的关系相对于array[first](或array[last])和array[pivot]的关系一致---------即同时大于或者同时小于,那么将first后移(或last前移)一位,继续比较,否则,交换两者位置。直到last不再大于first,至此完成一趟分割。

代码实现:

#!/usr/bin/python
# Filename: QuickSort.py

__author__ = 'iHippie'
__mail__ = 'ihippy@163.com'
__date__ = '$Date: 2013/05/06 $'

def quickSort(array, first, last):
low, high = first, last
pivot = low
while low < high:
while (pivot < high and array[pivot] <= array[high]) or (pivot > high and array[pivot] >= array[high]):
high -= 1
array[pivot], array[high] = array[high], array[pivot]
pivot = high

while (pivot < low and array[pivot] <= array[low]) or (pivot > low and array[pivot] >= array[low]):
low += 1
array[pivot], array[low] = array[low], array[pivot]
pivot = low

if first < last:
quickSort(array, first, pivot-1)
quickSort(array, pivot+1, last)

# --------------------------Test----------------------------
import random

a = []
for i in range(20):
a.append(random.randint(0, 500))

print 'Before sort: '
print a

quickSort(a, 0, len(a)-1)

print 'After sort: '
print a


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: