演算法——python實現快速排序(二分法思想),python二分法

來源:互聯網
上載者:User

演算法——python實現快速排序(二分法思想),python二分法
實現思路

  將所需要的數字存入一個列表中

看你就明白了:

實現代碼
 1 # coding: utf-8 2 # 快速排序,利用二分思想實現 3  4  5 def quick_sort(list, left, right): 6     if left > right: 7         return 8     temp = list[left] 9     i = left10     j = right11     while i != j:12         # 先從右向左尋找13         while list[j] >= temp and i < j:14             j -= 115         # 再從左向右尋找16         while list[i] <= temp and i < j:17             i += 118         if i < j:19             t = list[i]20             list[i] = list[j]21             list[j] = t22     # 基準數替換23     list[left] = list[i]24     list[i] = temp25     # 遞迴調用26     quick_sort(list, left, i - 1)27     quick_sort(list, i + 1, right)28 29 30 while True:31     list = []32     try:33         num = int(input('你想比較幾個數?\n'))34     except ValueError:35         continue36     for k in range(num):37         a = int(input('請輸入第' + str(k+1) + '個數:\n'))38         list.append(a)39     quick_sort(list, 0, num-1)40     print('排序結果為:')41     for l in range(len(list)):42         print(list[l], end=' ')43     print()

快速排序比較冒泡排序效率要高得多~

聯繫我們

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