Created
August 21, 2014 14:08
-
-
Save OzTamir/98e37998bbaad1d5dd82 to your computer and use it in GitHub Desktop.
Merge sort in 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
| # merge() takes two sorted lists and merge them into one sorted list | |
| from heapq import merge | |
| def merge_sort(m): | |
| ''' Sort a list in O(n * log(n)) ''' | |
| # If theres only one element in the list, return the list | |
| if len(m) <= 1: | |
| return m | |
| # Split the list into two equal-sized sub-lists | |
| middle = len(m) / 2 | |
| left = m[:middle] | |
| right = m[middle:] | |
| # Recursivly sort each half | |
| left = merge_sort(left) | |
| right = merge_sort(right) | |
| # Merge the two lists into one sorted list and return it | |
| return list(merge(left, right)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment