Python版將兩個有序數組合并為一個有序數組

來源:互聯網
上載者:User

標籤:return   替代   代碼   排序演算法   方法   比較   排序   也會   有序性   

第一種思路,把兩個數組合為一個數組然後再排序,問題又迴歸到冒泡和快排了,沒有用到兩個數組的有序性。(不好)

第二種思路,迴圈比較兩個有序數組頭位元素的大小,並把頭元素放到新數組中,從老數組中刪掉,直到其中一個數組長度為0。然後再把不為空白的老數組中剩下的部分加到新數組的結尾。(好)

第二種思路的排序演算法與測試代碼如下:

def merge_sort(a, b):    ret = []    while len(a)>0 and len(b)>0:        if a[0] <= b[0]:            ret.append(a[0])            a.remove(a[0])            if a[0] >= b[0]:            ret.append(b[0])            b.remove(b[0])    if len(a) == 0:        ret += b    if len(b) == 0:        ret += a    return retif __name__ == ‘__main__‘:    a = [1,3,4,6,7,78,97,190]    b = [2,5,6,8,10,12,14,16,18]    print(merge_sort(a, b))

反思了一下上面的過程,不應該用remove方法,因為仔細想一下remove方法裡面也會涉及遍曆,不算最簡單。

改進一下,改用索引元素比較法替代頭位元素比較法:

def merge_sort(a, b):    ret = []    i = j = 0    while len(a) > i + 1 and len(b) > j + 1:        if a[i] <= b[j]:            ret.append(a[i])            i += 1        else:            ret.append(b[j])            j += 1    if len(a) > i + 1:        ret += a[i:]    if len(b) > j + 1:        ret += b[j:]    return retif __name__ == ‘__main__‘:    a = [1,3,4,6,7,78,97,190]    b = [2,5,6,8,10,12,14,16,18]    print(merge_sort(a, b))

這個基本就是最簡單的方法了。

 

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.