Last active
June 19, 2018 08:18
-
-
Save xuhang57/6424d09b5eca996985507ff00aa9cbd2 to your computer and use it in GitHub Desktop.
Merge Sort
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 merge(left, right): | |
| res = [] | |
| i, j = 0, 0 | |
| while i < len(left) and j < len(right): | |
| if left[i] <= right[j]: | |
| res.append(left[i]) | |
| i+=1 | |
| else: | |
| res.append(right[j]) | |
| j+=1 | |
| res += left[i:] | |
| res += right[j:] | |
| return res | |
| def merge_sort(arr): | |
| if len(arr) <= 1: | |
| return arr | |
| mid = int(len(arr) / 2) | |
| left = merge_sort(arr[:mid]) | |
| right = merge_sort(arr[mid:]) | |
| return merge(left, right) | |
| merge_sort([12,4,5,6,3,7,15,1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment