Created
July 12, 2020 12:17
-
-
Save blacktrub/8f269aa228659c8b80487689be2e7872 to your computer and use it in GitHub Desktop.
merge sort algorithm
This file contains hidden or 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
| import math | |
| def merge(one, two): | |
| n = max(len(one), len(two)) | |
| i, j = 0, 0 | |
| result = [] | |
| for _ in range(n * 2): | |
| a = one[i] if len(one) > i else None | |
| b = two[j] if len(two) > j else None | |
| if a is not None and b is not None: | |
| if a < b: | |
| result.append(a) | |
| i += 1 | |
| else: | |
| result.append(b) | |
| j += 1 | |
| elif a is not None: | |
| result.append(a) | |
| i += 1 | |
| elif b is not None: | |
| result.append(b) | |
| j += 1 | |
| return result | |
| def merge_sort(arr): | |
| if len(arr) < 2: | |
| return arr | |
| n2 = int(math.ceil(float(len(arr)) / 2)) | |
| c = merge_sort(arr[:n2]) | |
| d = merge_sort(arr[n2:]) | |
| return merge(c, d) | |
| if __name__ == '__main__': | |
| arr = [9, 4, 2, 1, 6, 0] | |
| result = merge_sort(arr) | |
| assert result == sorted(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment