From f044a497cac9c2fb7133324f8a78988d7a3e7d4c Mon Sep 17 00:00:00 2001 From: Sarthak Jain <61319250+thesarthakjain@users.noreply.github.com> Date: Sun, 4 Oct 2020 21:49:08 +0530 Subject: [PATCH] Merge sort added to python. --- python/Merge Sort | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 python/Merge Sort diff --git a/python/Merge Sort b/python/Merge Sort new file mode 100644 index 0000000..1e74358 --- /dev/null +++ b/python/Merge Sort @@ -0,0 +1,33 @@ +def merge_sort(unsorted_list): + if len(unsorted_list) <= 1: + return unsorted_list +# Find the middle point and devide it + middle = len(unsorted_list) // 2 + left_list = unsorted_list[:middle] + right_list = unsorted_list[middle:] + + left_list = merge_sort(left_list) + right_list = merge_sort(right_list) + return list(merge(left_list, right_list)) + +# Merge the sorted halves + +def merge(left_half,right_half): + + res = [] + while len(left_half) != 0 and len(right_half) != 0: + if left_half[0] < right_half[0]: + res.append(left_half[0]) + left_half.remove(left_half[0]) + else: + res.append(right_half[0]) + right_half.remove(right_half[0]) + if len(left_half) == 0: + res = res + right_half + else: + res = res + left_half + return res + +unsorted_list = [64, 34, 25, 12, 22, 11, 90] + +print(merge_sort(unsorted_list))