How to Implement Merge Sort in Python

In this tutorial, we will learn "How to Implement Merge Sort in Python". The main objective is to understand and implement merge sort. This guide will walk you step by step through the process, making it easier to follow and apply. By the end of this tutorial, you will have a solid understanding of how merge sort works in Python, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.

This topic is straightforward and easy to understand. By following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of implementing Merge Sort. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding in Python.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def merge_sort(arr, start, end):
  2.     if start >= end:
  3.         return
  4.  
  5.     mid = (start + end) // 2
  6.     merge_sort(arr, start, mid)
  7.     merge_sort(arr, mid + 1, end)
  8.     merge(arr, start, mid, end)
  9.  
  10.  
  11. def merge(arr, start, mid, end):
  12.     left = arr[start:mid + 1]
  13.     right = arr[mid + 1:end + 1]
  14.  
  15.     i = j = 0
  16.     k = start
  17.  
  18.     while i < len(left) and j < len(right):
  19.         if left[i] <= right[j]:
  20.             arr[k] = left[i]
  21.             i += 1
  22.         else:
  23.             arr[k] = right[j]
  24.             j += 1
  25.         k += 1
  26.  
  27.     # Copy remaining elements
  28.     while i < len(left):
  29.         arr[k] = left[i]
  30.         i += 1
  31.         k += 1
  32.  
  33.     while j < len(right):
  34.         arr[k] = right[j]
  35.         j += 1
  36.         k += 1
  37.  
  38.  
  39. # MAIN LOOP
  40. while True:
  41.     print("\n========== Implement Merge Sort ==========\n")
  42.  
  43.     # Input handling
  44.     try:
  45.         user_input = input("Enter numbers to sort (space-separated): ").strip()
  46.         if not user_input:
  47.             print("Input cannot be empty.")
  48.             continue
  49.  
  50.         arr = [int(x) for x in user_input.split()]
  51.     except ValueError:
  52.         print("Invalid input. Please enter integers only.")
  53.         continue
  54.  
  55.     print(f"Original list: {arr}")
  56.  
  57.     # Perform merge sort
  58.     merge_sort(arr, 0, len(arr) - 1)
  59.  
  60.     print(f"Sorted list:   {arr}")
  61.  
  62.     # Try Again Option
  63.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  64.     if opt == "no":
  65.         print("Exiting program...")
  66.         break
  67.     elif opt != "yes":
  68.         print("Invalid choice. Exiting program...")
  69.         break

This Python program implements Merge Sort, a divide-and-conquer sorting algorithm that recursively splits a list into smaller sublists, sorts them, and then merges them back together in order. It defines a `merge_sort` function to divide the list and a `merge` function to combine sorted sublists. The program runs interactively, allowing users to input a list of integers, view the original list, and see the sorted result. It also includes input validation and a loop that lets users repeat the process or exit.

Output:

There you have it we successfully created How to Implement Merge Sort in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials