Python實現歸併排序

來源:互聯網
上載者:User

標籤:自身   ini   body   一個   數字   pen   font   proc   序列   

歸併排序執行過程:
          1、執行歸併排序函數時,把全部的數字一分為二,繼續遞迴調用函數自身,左一半右一半的劃分開,直到每一份裡只有一個元素為止,停止劃分。
         2、把劃分開的元素按照大小順序排列,先 1 1,合并為個數為 2 的數組,再把 2 2 按順序大小要求合并成個數為 4 的數組,依次進行把所有元素按大小排序
            兩兩合并時兩序列均已是有序序列

如:
    4 1 3 10 7 3 5 0
    
    4 1 3 10 7 3 5 0

    4 1 3 10 7 3 5 0

    4 1 3 10 7 3 5 0 //每一組個數為 1 結束



合并:  1 4 3 10 3 7 0 5

      1 3 4 10 0 3 5 7

最後結果:   0 1 3 3 4 5 7 10



目標序列: l = [1000, 5, 6, 7, 3, 30, 25, 12, 9, 13, 10, 8]
def mergesort(left, mid, right):    l_1, l_2 = l[left:mid], l[mid:right]    print("歸併前:", l_1, l_2)    len1 = len(l_1)    len2 = len(l_2)    a, b, l3 = 0, 0, []    while a < len1 and b < len2:        if l_1[a] <= l_2[b]:            l3.append(l_1[a])            a += 1        else:            l3.append(l_2[b])            b += 1    while a < len1:        l3.append(l_1[a])        a += 1    while b < len2:        l3.append(l_2[b])        b += 1    l[left:right] = l3[:]    print("後:", l)def sor(left, right):    if left < right:        mid = int((left + right) / 2)        sor(left, mid)        sor(mid+1, right)        mergesort(left, mid+1, right+1)sor(0, 11)print("\n完畢:", l)

 

執行過程

歸併前: [1000] [5]後: [5, 1000, 6, 7, 3, 30, 25, 12, 9, 13, 10, 8]歸併前: [5, 1000] [6]後: [5, 6, 1000, 7, 3, 30, 25, 12, 9, 13, 10, 8]歸併前: [7] [3]後: [5, 6, 1000, 3, 7, 30, 25, 12, 9, 13, 10, 8]歸併前: [3, 7] [30]後: [5, 6, 1000, 3, 7, 30, 25, 12, 9, 13, 10, 8]歸併前: [5, 6, 1000] [3, 7, 30]後: [3, 5, 6, 7, 30, 1000, 25, 12, 9, 13, 10, 8]歸併前: [25] [12]後: [3, 5, 6, 7, 30, 1000, 12, 25, 9, 13, 10, 8]歸併前: [12, 25] [9]後: [3, 5, 6, 7, 30, 1000, 9, 12, 25, 13, 10, 8]歸併前: [13] [10]後: [3, 5, 6, 7, 30, 1000, 9, 12, 25, 10, 13, 8]歸併前: [10, 13] [8]後: [3, 5, 6, 7, 30, 1000, 9, 12, 25, 8, 10, 13]歸併前: [9, 12, 25] [8, 10, 13]後: [3, 5, 6, 7, 30, 1000, 8, 9, 10, 12, 13, 25]歸併前: [3, 5, 6, 7, 30, 1000] [8, 9, 10, 12, 13, 25]後: [3, 5, 6, 7, 8, 9, 10, 12, 13, 25, 30, 1000]完畢: [3, 5, 6, 7, 8, 9, 10, 12, 13, 25, 30, 1000]Process finished with exit code 0

 

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.