Created
August 24, 2016 17:03
-
-
Save davidejones/9f7b0e6efd434c032231204c8c35bae5 to your computer and use it in GitHub Desktop.
first attempt at a 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_sort(l, first_iteration=False): | |
| data = [] | |
| if first_iteration: | |
| return merge_sort([[i] for i in l]) | |
| else: | |
| for i in xrange(0, len(l), 2): | |
| left, right = l[i], l[i+1] if i != len(l)-1 else [] | |
| subdata = [] | |
| for l_item in list(left): | |
| for r_item in list(right): | |
| if l_item < r_item: | |
| subdata.append(l_item) | |
| left.remove(l_item) | |
| break | |
| elif r_item < l_item: | |
| subdata.append(r_item) | |
| right.remove(r_item) | |
| subdata += left + right | |
| data.append(subdata) | |
| return [y for x in data for y in x] if len(data) == 1 else merge_sort(data) | |
| if __name__ == '__main__': | |
| my_list = [1, 12, 4, 7, 3, 5, 2, 6, 11, 10, 9, 13, 8] | |
| print(merge_sort(my_list, True)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment