Last active
April 12, 2019 03:00
-
-
Save DiegoGallegos4/8f1c00ff110d6c07402f95f72ab0f865 to your computer and use it in GitHub Desktop.
Merge Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def merge(A, B): | |
C = [] | |
while len(A) and len(B): | |
a, b = A[0], B[0] | |
if a <= b: | |
C.append(A.pop(0)) | |
else: | |
C.append(B.pop(0)) | |
while len(A): | |
C.append(A.pop(0)) | |
while len(B): | |
C.append(B.pop(0)) | |
return C | |
def merge_sort(A): | |
""" | |
Sort an array A[0..n] | |
Running time: | |
O(nlogn) | |
T(n) = 2 * T(n/2) + O(n) | |
d = 1, a = 2, b = 2 | |
so by master theorem | |
d = logb(a) | |
1 = log2(2) == 1 (O(n^d * log(n)) | |
""" | |
if len(A) == 1: | |
return A | |
midpoint = len(A) // 2 | |
B = merge_sort(A[:midpoint]) | |
C = merge_sort(A[midpoint:]) | |
return merge(B, C) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment