Merge Sort

Sort an array using the merge sort algorithm with O(n log n) time complexity.

Code

Algorithms
def merge_sort(a):
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
    result = []
    while left and right:
        result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
    return result + left + right
return merge_sort(arr)

Parameters

Array to sort

Server

More Python Snippets