快速排序的演算法思想及Python版快速排序的實現樣本,python樣本

來源:互聯網
上載者:User

快速排序的演算法思想及Python版快速排序的實現樣本,python樣本

快速排序是C.R.A.Hoare於1962年提出的一種劃分交換排序。它採用了一種分治的策略,通常稱其為分治法(Divide-and-ConquerMethod)。

1.分治法的基本思想

分治法的基本思想是:將原問題分解為若干個規模更小但結構與原問題相似的子問題。遞迴地解這些子問題,然後將這些子問題的解組合為原問題的解。

2.快速排序的基本思想

設當前待排序的無序區為R[low..high],利用分治法可將快速排序的基本思想描述為:

(1)分解:

在R[low..high]中任選一個記錄作為基準(Pivot),以此基準將當前無序區劃分為左、右兩個較小的子區間R[low..pivotpos-1)和R[pivotpos+1..high],並使左邊子區間中所有記錄的關鍵字均小於等於基準記錄(不妨記為pivot)的關鍵字pivot.key,右邊的子區間中所有記錄的關鍵字均大於等於pivot.key,而基準記錄pivot則位於正確的位置(pivotpos)上,它無須參加後續的排序。

注意:

劃分的關鍵是要求出基準記錄所在的位置pivotpos。劃分的結果可以簡單地表示為(注意pivot=R[pivotpos]):

R[low..pivotpos-1].keys≤R[pivotpos].key≤R[pivotpos+1..high].keys

其中low≤pivotpos≤high。

(2)求解:

通過遞迴調用快速排序對左、右子區間R[low..pivotpos-1]和R[pivotpos+1..high]快速排序。

(3)組合:

因為當"求解"步驟中的兩個遞迴調用結束時,其左、右兩個子區間已有序。對快速排序而言,"組合"步驟無須做什麼,可看作是空操作。

Python實現

原理: 先用初始資料, 然後對這個資料進行排序使左邊的資料小於
該資料,右邊的大於該資料,然後用遞迴的方法對兩邊的資料進行依次排序。

#!/usr/bin/env python#_*_coding:utf-8_*_ def rand(x): import random if x < 3:  x = 5 if x > 1000:  print "big data"  return [] l = range(1, x) li = [] while l:  r = random.randint(0, len(l)-1)  li.append(l.pop(r)) return lidef quicksort(l, low, hight): key = l[low] while low < hight:  while key <= l[hight] and low < hight:   hight -= 1  l[low], l[hight] = l[hight], l[low]  while key >= l[low] and low < hight:   low += 1  l[low], l[hight] = l[hight], l[low] l[hight] = key return hightdef m_sort(l, low, hight): if low >= hgiht:  return  index = quicksort(l, low, hight) m_sort(l, low, index) m_sort(l, index+1, hight)def main(): l = rand(1500) m_sort(l, 0, len(l)-1) print lif __name__ == '__main__': main()

聯繫我們

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