Merge sort in python
Here you will get an example to write a Python program merge sort. To write a Python program for merge sort, you need to divide the list into smaller sublists, sort those sublists, and then merge them back together.
Example to write a python program merge sort
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | def merge_sort(arr): if len(arr) > 1: mid = len(arr) // # Finding the middle of the array left_half = arr[:mid] # Dividing the elements into 2 halves right_half = arr[mid:] merge_sort(left_half) # Sorting the first half merge_sort(right_half) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] 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 # Checking if any element was left 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 def print_list(arr): for i in range(len(arr)): print(arr[i], end=" ") print() # Driver code to test the above implementation if __name__ == "__main__": arr = [10, 9, 11, 25, 16, 7] print("Given array is:") print_list(arr) merge_sort(arr) print("Sorted array is:") print_list(arr) |
Output
Given array is:
10 9 11 25 16 7
Sorted array is:
7 9 10 11 16 25
Check out our other Python programming examples