Merge Sort Implementation in Python
Today I post the python implementation of merge sort. This is straight-forward implementation of the algorithm presented in the book Introduction to Algorithms [CLRS]. If you think the implementation can be more Pythonic, feel free to comment. Here is my code: def merge(li, start, mid, end): left_li = [] left_li.extend(li[start : mid+1]) right_li = [] right_li.extend(li[mid+1: end+1]) left_li.append(2147483647) right_li.append(2147483647) i = 0 j = 0 for k in range(start, end+1): if left_li[i] <= right_li[j]: li[k] = left_li[i] i += 1 else: li[k] = right_li[j] j += 1 def merge_sort(li, start, end): if start < end: mid = (start + end) / 2 merge_sort(li, start, mid) merge_sort(li, mid+1, end) merge(li, start, mid, end) if __name__ == "__main__": li = [5, 2, 4, 7, 1, 3, 2, 6, -4] print li merge_sort(li, 0, len(li)-1) print li You can test the merge sort implementation against this problem: