Last active
September 15, 2015 05:52
-
-
Save rishi93/47c0e64547dbc51ba6d5 to your computer and use it in GitHub Desktop.
Mergesort
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): | |
| result = [] | |
| while len(left) > 0 and len(right) > 0: | |
| if left[0] < right[0]: | |
| result.append(left[0]) | |
| left = left[1:] | |
| else: | |
| result.append(right[0]) | |
| right = right[1:] | |
| if len(left) > 0: | |
| result.extend(left) | |
| elif len(right) > 0: | |
| result.extend(right) | |
| return result | |
| def merge_sort(arr): | |
| if len(arr) <= 1: | |
| return arr | |
| mid = len(arr) // 2 | |
| left = arr[:mid] | |
| right = arr[mid:] | |
| left = merge_sort(left) | |
| right = merge_sort(right) | |
| return merge(left,right) | |
| arr = [6,5,4,2,1,3] | |
| print(merge_sort(arr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment