Python Program for Merge Sort
In this tutorial, we will discuss a Python program for merge sort algorithm to sort an array of numbers in ascending order.
Before going to the program first, let us understand what is Merge Sort.
Merge Sort:
- Merge sort is a divide-and-conquer sorting algorithm that divides the array into two halves, sorts each half, and then merges them back together.
Related: Python program for Quick Sort
Program code for Merge Sort in Python
# Merge Sort in Python def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 arr = [12, 11, 13, 5, 6, 7] merge_sort(arr) print("Sorted array:", arr)
Explanation
- Function Definition: The
merge_sort
function takes an arrayarr
as input and sorts it in ascending order using the merge sort algorithm. - Main Program: The program defines an unsorted array and sorts it using the
merge_sort
function. It then prints the sorted array.
Output
- When you run the above program, it will sort the array using merge sort and print the sorted result.
Conclusion
- In this tutorial, we learned how to implement the merge sort algorithm in Python.
- Understanding this concept is essential for solving various sorting problems and enhancing your programming skills.