美文网首页
2019-03-25 Basic Algorithms - So

2019-03-25 Basic Algorithms - So

作者: ANPULI | 来源:发表于2019-03-26 03:36 被阅读0次

    Divide & Conquer

    Example: Binary Search

    Given sorted A[1..n] and number x. Find out whether A contains x.

    Complexity: O(\log{n})

    Sorting

    Input

    Array A[1..n] of numbers

    Output

    Sorted A[1..n] in ascending order

    Merge Sort

    Merge

    Suppose we have two sorted arrays:
    B: 1, 5, 12
    C: 2, 3, 7

    and we want to combine the two arrays to get
    1, 2, 3, 5, 7, 12

    def merge(L, R):
        i = j = 0
        result = []
        while i < len(L) and j < len(R):
            if L[i] <= R[j]:
                result.append(L[i])
                i += 1
            else:
                result.append(R[j])
                j += 1
        while i < len(L):
            result.append(L[i])
            i += 1
        while j < len(R):
            result.append(R[j])
            j += 1
        return result
    

    The complexity is O(m+n), m = len(L), n = len(R)

    def merge_sort(A):
        if len(A) == 1:
            return A
        m = len(A) // 2
        L = merge_sort(A[:m])
        R = merge_sort(A[m:])
        return merge(L, R)
    

    相关文章

      网友评论

          本文标题:2019-03-25 Basic Algorithms - So

          本文链接:https://www.haomeiwen.com/subject/vsgivqtx.html