快排用Python的實現 - 簡潔方式

來源:互聯網
上載者:User

標籤:分享   ret   交換   實現   bsp   圖片   rtt   學習   分割   

 

因為最近在學習Python,這篇是我入手學習的第一個小例子,是跟著這個代碼,又重新用自己的想法寫出來的,也作為初期的參考資料吧。如果也有新人在學習這裡,可以看一下

源地址:https://www.cnblogs.com/yekwol/p/5778040.html

 

 

快速排序基本思想是:通過一趟排序將要排序的資料分割成獨立的兩部分,其中一部分的所有資料都比另外一部分的所有資料都要小,然後再按此方法對這兩部分資料分別進行快速排序,整個排序過程可以遞迴進行,以此達到整個資料變成有序序列。

如序列[6,8,1,4,3,9],選擇6作為基準數。從右向左掃描,尋找比基準數小的數字為3,交換6和3的位置,[3,8,1,4,6,9],接著從左向右掃描,尋找比基準數大的數字為8,交換6和8的位置,[3,6,1,4,8,9]。重複上述過程,直到基準數左邊的數字都比其小,右邊的數字都比其大。然後分別對基準數左邊和右邊的序列遞迴進行上述方法。

實現代碼如下:

 1 def parttion(v, left, right): 2     key = v[left] 3     low = left 4     high = right 5     while low < high: 6         while (low < high) and (v[high] >= key): 7             high -= 1 8         v[low] = v[high] 9         while (low < high) and (v[low] <= key):10             low += 111         v[high] = v[low]12         v[low] = key13     return low14 def quicksort(v, left, right):15     if left < right:16         p = parttion(v, left, right)17         quicksort(v, left, p-1)18         quicksort(v, p+1, right)19     return v20 21 s = [6, 8, 1, 4, 3, 9, 5, 4, 11, 2, 2, 15, 6]22 print("before sort:",s)23 s1 = quicksort(s, left = 0, right = len(s) - 1)24 print("after sort:",s1)

運行結果:

before sort: [6, 8, 1, 4, 3, 9, 5, 4, 11, 2, 2, 15, 6]after sort: [1, 2, 2, 3, 4, 4, 5, 6, 6, 8, 9, 11, 15]

快排用Python的實現 - 簡潔方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.