python Quicksort demo

來源:互聯網
上載者:User

標籤:

__author__ = ‘student‘‘‘‘quicksortstep 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 pivotpivot=1  [4] 5 7 3 20 9 [j]then scan from left side, find data greater than pivot, then swap the position j and i4 [] 7 3 20 9 5when 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 somethingstep 3. then you have two parts to sort, left part and right part.recursive  call this method to sort‘‘‘import randomdef 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 syssys.setrecursionlimit(999)la=[]def generatenumbers(la,len):    for x in range(len):        la.extend([random.randint(1,50)])generatenumbers(la,1000)print laquicksort(la,0,len(la)-1)print la

python Quicksort demo

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.