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

python实现快速排序算法(两种不同实现方式)

时间:2014-05-18 04:13:10      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:快速排序   python   

# -*- coding: utf-8 -*-
"""
Created on Fri May 16 17:24:05 2014

@author: lifeix
"""

#快速排序
import sys
import random

length = 30

def qsort(arr,left,right):
    lp = left
    rp = right
    if lp == rp:return
    while True:
        while arr[lp] >= arr[right] and rp > lp:
            lp = lp +1
        while arr[rp] <= arr[right] and rp > lp:
            rp = rp - 1
        arr[lp],arr[rp] = arr[rp],arr[lp]
        if lp >= rp:
            break
    arr[rp],arr[right] = arr[right],arr[lp]
    if left < lp:
        qsort(arr,left,lp - 1)
    qsort(arr,rp,right)
    
def main():
    arr = []
    sys.setrecursionlimit(100000)
    for i in range(length):
        arr.append(random.randint(0,10000))
    qsort(arr,0,length-1)
    print arr
if __name__ == ‘__main__‘:
    for i in range(10):
        main()
#快速排序第二种实现
def quickSort(arr,p,r):
    if p < r:
        q = partition(arr,p,r)
        quickSort(arr,p,q - 1)
        quickSort(arr,q+1,r)
        
def partition(arr,p,r):
    x = arr[r]
    i = p
    for j in range(p,r):
        if arr[j] < x:
            arr[i],arr[j] = arr[j],arr[i]
            i = i + 1
    arr[i],arr[r] = arr[r],arr[i]
    return i
    
if __name__ == ‘__main__‘:
    arr = [1,3,89,2,0,78,98,23,56,100]
    quickSort(arr,0,len(arr) - 1)
    print arr


python实现快速排序算法(两种不同实现方式),布布扣,bubuko.com

python实现快速排序算法(两种不同实现方式)

标签:快速排序   python   

原文地址:http://blog.csdn.net/startupmount/article/details/26004931

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