码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序

时间:2016-11-02 14:43:36      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:end   style   and   code   class   dex   代码   for   port   

发现自己写起来很不顺手,得从最右边找出pivot元素是最方便的!

以最左边的元素作为pivot的代码,看到好多坑:

def qsort(arr, left, right):
    if left >= right:
        return
    pivot = arr[left]
    p = left+1
    for i in range(left+1, right+1):
        if arr[i] < pivot:
            arr[i], arr[p] = arr[p], arr[i]
            p += 1
    partition_index = p-1
    arr[left], arr[partition_index] = arr[partition_index], arr[left]
    qsort(arr, left, partition_index-1)
    qsort(arr, partition_index+1, right)

def qsort2(arr, left, right):
    if left >= right:
        return
    pivot = arr[right]
    index = left
    for i in range(left, right):
        if arr[i] < pivot:
            arr[i], arr[index] = arr[index], arr[i]
            index += 1
    arr[index], arr[right] = arr[right], arr[index]
    qsort(arr, left, index-1)
    qsort(arr, index+1, right)

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

print a
qsort2(a, 0, len(a)-1)
print a

输出:

[12, 4, 19, 2, 15, 13, 16, 2, 4, 1, 0, 13, 10, 1, 11, 15, 13, 7, 8, 6, 12, 20, 18, 20, 20, 3, 7, 5, 11, 11]
[0, 1, 1, 2, 2, 3, 4, 4, 5, 6, 7, 7, 8, 10, 11, 11, 11, 12, 12, 13, 13, 13, 15, 15, 16, 18, 19, 20, 20, 20]

 

快速排序

标签:end   style   and   code   class   dex   代码   for   port   

原文地址:http://www.cnblogs.com/bonelee/p/6022591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!