Merge Sort Algorithm

This code is a python implementation of the merge sort algorithm. The algorithm is a divide and conquer method of sorting elements in a list. It divides the input list into two halves until there are individual elements and then starts merging the elements back while comparing and sorting them.

Code Example

def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2  # Finding the middle of the array
        L = arr[:mid]        # Dividing the elements into 2 halves
        R = arr[mid:]

        merge_sort(L)        # Sorting the first half
        merge_sort(R)        # Sorting the second half

        i = j = k = 0

        # Copy data to temporary arrays L[] and R[]
        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

        # Checking if any element was left
        while i < len(L):
            arr[k] = L[i]
            i += 1
            k += 1

        while j < len(R):
            arr[k] = R[j]
            j += 1
            k += 1
    return arr

# Example usage
arr = [12, 11, 13, 5, 6, 7]
sorted_arr = merge_sort(arr)
print("Sorted array is:", sorted_arr)

Output

Sorted array is: [5, 6, 7, 11, 12, 13]

Merge Sort is an efficient, stable, and comparison-based sorting algorithm with a time complexity of O(n log n) in the best, average, and worst cases. It works well for large datasets and is often used in real-world applications.

Code Explanation

Function Definition

def merge_sort(arr):
  • The function merge_sort is defined to take a single list arr as its parameter.

Base Case

    if len(arr) > 1:
  • The function checks if the length of arr is greater than 1. If not, the array is already sorted (or empty), and the function returns immediately.

Finding the Middle

        mid = len(arr) // 2
  • The midpoint of arr is found using integer division. This will be used to split the array into two halves.

Dividing the Array

        L = arr[:mid]
        R = arr[mid:]
  • The array arr is split into two halves: L (left half) and R (right half).

Recursive Sorting

        merge_sort(L)
        merge_sort(R)
  • The function recursively sorts the left half L and the right half R.

Merging the Sorted Halves

        i = j = k = 0
  • Three indices i, j, and k are initialized to 0. i will track the current index of L, j will track the current index of R, and k will track the current index of the merged array arr.

Comparing and Merging

        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
  • A while loop runs as long as there are elements in both L and R. The elements of L and R are compared, and the smaller element is added to arr. The indices i, j, and k are updated accordingly.

Remaining Elements in L

        while i < len(L):
            arr[k] = L[i]
            i += 1
            k += 1
  • After the initial merging, there might be remaining elements in L (if any). These elements are copied to arr.

Remaining Elements in R

        while j < len(R):
            arr[k] = R[j]
            j += 1
            k += 1
  • Similarly, any remaining elements in R are copied to arr.

Return Statement

    return arr
  • The sorted array arr is returned.

Example Usage

arr = [12, 11, 13, 5, 6, 7]
sorted_arr = merge_sort(arr)
print("Sorted array is:", sorted_arr)
  • An example list arr is sorted using the merge_sort function, and the sorted list is printed.