python Quicksort demo

__author__ = 'student'

'''
quicksort
step 1, choose one pivot, such as pivot=la[0]
step 2, scan the data from right side, find data less than pivot, then swap this with pivot
pivot=1  [4] 5 7 3 20 9 [j]
then scan from left side, find data greater than pivot, then swap the position j and i
4 [] 7 3 20 9 5
when i>=j then finish one loop. then put the pivot in the i;
 all data are dived by pivot now. left is less than pivot and right are greater than pivot.
think step by step then do it and try something
step 3. then you have two parts to sort, left part and right part.
recursive  call this method to sort
'''
import random

def quicksort(la,l,r):
    if l>=r :
        return
    left=l;right=r
    pivot=la[left]
    while left < right:
        while left<right and la[right]>pivot:
            right-=1
        if left<right :
            la[left]=la[right]
            left+=1
        while left<right and la[left]<pivot:
            left+=1
        if left<right:
            la[right]=la[left]
    la[left]=pivot
    quicksort(la,l,left-1)
    quicksort(la,left+1,r)

def quicksort2(la):
    if len(la)<=1:
        return la
    return quicksort2([lt for lt in la[1:] if lt<la[0]])+ la[0:1]+quicksort2([ge for ge in la[1:] if ge>=la[0]])

import sys
sys.setrecursionlimit(999)

la=[]
def generatenumbers(la,len):
    for x in range(len):
        la.extend([random.randint(1,50)])
generatenumbers(la,1000)
print la
quicksort(la,0,len(la)-1)
print la

转载于:https://www.cnblogs.com/huaxiaoyao/p/4489805.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值