Created
April 29, 2017 07:12
-
-
Save mlshv/616735cf3ca09138a62437a1aaa6c8c2 to your computer and use it in GitHub Desktop.
Recursive Merge Sort (Python)
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
| def divide(a): | |
| return a[:len(a)//2], a[len(a)//2:] | |
| def merge(a, b): | |
| result = [] | |
| while(True): | |
| if len(a) == 0: | |
| result += b | |
| break | |
| elif len(b) == 0: | |
| result += a | |
| break | |
| if a[0] < b[0]: | |
| result.append(a.pop(0)) | |
| else: | |
| result.append(b.pop(0)) | |
| return result | |
| def merge_sort_recursive(a): | |
| a, b = divide(a) | |
| if len(a) == 0 or len(b) == 0: | |
| return merge(a, b) | |
| a = merge_sort_recursive(a) | |
| b = merge_sort_recursive(b) | |
| return merge(a, b) | |
| if __name__ == '__main__': | |
| import random | |
| a = random.sample(range(30), 11) | |
| print(merge_sort_recursive(a)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment