From 10b1204fc4effdcec1a98ed31118b7769efc9b98 Mon Sep 17 00:00:00 2001 From: ashu9335 <115342974+ashu9335@users.noreply.github.com> Date: Sun, 29 Oct 2023 21:41:01 +0545 Subject: [PATCH] Create Merge Sort --- Merge Sort | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Merge Sort diff --git a/Merge Sort b/Merge Sort new file mode 100644 index 0000000..5349627 --- /dev/null +++ b/Merge Sort @@ -0,0 +1,36 @@ +def merge_sort(arr): + if len(arr) > 1: + mid = len(arr) // 2 # Find the middle of the array + left_half = arr[:mid] # Divide the array into two halves + right_half = arr[mid:] + + # Recursively call merge_sort on both halves + merge_sort(left_half) + merge_sort(right_half) + + i = j = k = 0 + + # Merge the two halves back together in sorted order + while i < len(left_half) and j < len(right_half): + if left_half[i] < right_half[j]: + arr[k] = left_half[i] + i += 1 + else: + arr[k] = right_half[j] + j += 1 + k += 1 + + while i < len(left_half): + arr[k] = left_half[i] + i += 1 + k += 1 + + while j < len(right_half): + arr[k] = right_half[j] + j += 1 + k += 1 + +# Example usage: +my_list = [38, 27, 43, 3, 9, 82, 10] +merge_sort(my_list) +print("Sorted array:", my_list)