Python的快速排序方法

來源:互聯網
上載者:User
這篇文章主要介紹了Python實現的快速排序演算法,結合執行個體形式分析了Python快速排序的原理、實現方法與相關操作技巧,需要的朋友可以參考下

本文執行個體講述了Python實現的快速排序演算法。分享給大家供大家參考,具體如下:

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

如序列[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]。重複上述過程,直到基準數左邊的數字都比其小,右邊的數字都比其大。然後分別對基準數左邊和右邊的序列遞迴進行上述方法。

實現代碼如下:


def parttion(v, left, right):  key = v[left]  low = left  high = right  while low < high:    while (low < high) and (v[high] >= key):      high -= 1    v[low] = v[high]    while (low < high) and (v[low] <= key):      low += 1    v[high] = v[low]    v[low] = key  return lowdef quicksort(v, left, right):  if left < right:    p = parttion(v, left, right)    quicksort(v, left, p-1)    quicksort(v, p+1, right)  return vs = [6, 8, 1, 4, 3, 9, 5, 4, 11, 2, 2, 15, 6]print("before sort:",s)s1 = quicksort(s, left = 0, right = len(s) - 1)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]

聯繫我們

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