[building block] merge sort @ Python

來源:互聯網
上載者:User

標籤:style   blog   color   io   ar   for   div   sp   log   

Here is the basic algorithm about merge sort:

def merge(s1,s2,s):    i=j=0    while i + j < len(s):        if j == len(s2) or (i < len(s1) and s1[i] < s2[j]):            s[i + j] = s1[i]            i += 1        else:            s[i + j] = s2[j]                j += 1           def merge_sort(s):    """ Sort the elements of python list s using merge-sort algorithm"""    # Time compelxity: O(nlogn), where n = len(s)    n = len(s)    if n < 2:        return    # Divide    mid = n // 2    s1 = s[:mid]    s2 = s[mid:]            #conquer (with recursion)    merge_sort(s1)    merge_sort(s2)        # merge results    merge(s1,s2,s)        

 

insertion sort: time complexity: O(n^2)

def insertion_sort(A):    ”””Sort list of comparable elements into nondecreasing order.”””    for k in range(1, len(A)): # from 1 to n-1        cur = A[k] # current element to be inserted        j = k # find correct index j for current        while j > 0 and A[j-1] > cur: # element A[j-1] must be after current            A[j] = A[j-1]            j -= 1        A[j] = cur # cur is now in the right place

 

[building block] merge sort @ 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.