利用Python實現歸併排序

來源:互聯網
上載者:User

標籤:conf   nal   實現   __name__   import   中斷   ext   number   while   

利用python進行歸併排序,摘抄自http://blog.csdn.net/minxihou/article/details/51821052

“代碼真的不是一氣呵成的,而且也不是想當然寫出來的。可能需要反覆斷點中斷來查看是否有邏輯錯誤。在理解了問題的基礎下我們需要先把大體的代碼架構最好先寫出來,
特別是主要的邏輯判斷語句。但是不需要太care我迴圈體或者判斷裡面語句怎麼實現,當你把這一步做到的時候能避免很多不必要的錯誤發生。”
 1 import random 2  3 def ConfiationAlgorithm(str): 4     if len(str) <= 1: #子序列 5         return str 6     mid = (len(str) // 2) 7     left = ConfiationAlgorithm(str[:mid])#遞迴的切片操作 8     right = ConfiationAlgorithm(str[mid:]) 9     result = []10     #i,j = 0,011 12     while len(left) > 0 and len(right) > 0:13         if (left[0] <= right[0]):14             #result.append(left[0])15             result.append(left.pop(0))16             #i+= 117         else:18             #result.append(right[0])19             result.append(right.pop(0))20             #j+= 121 22     if (len(left) > 0):23         result.extend(ConfiationAlgorithm(left))24     else:25         result.extend(ConfiationAlgorithm(right))26     return result27 28 if __name__ == ‘__main__‘:29     a = [20,30,64,16,8,0,99,24,75,100,69]30     print(ConfiationAlgorithm(a))31     b = [random.randint(1,1000) for i in range(10)]32     print(ConfiationAlgorithm(b))

另一種思路

 1 def merge(left, right): 2     i, j = 0, 0 3     result = [] 4     while i < len(left) and j < len(right): 5         if left[i] <= right[j]: 6             result.append(left[i]) 7             i += 1 8         else: 9             result.append(right[j])10             j += 111     result += left[i:]12     result += right[j:]13     return result14 15 def merge_sort(lists):16     # 歸併排序17     if len(lists) <= 1:18         return lists19     num = len(lists) / 220     left = merge_sort(lists[:num])21     right = merge_sort(lists[num:])22     return merge(left, right)

 

 

利用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.