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.
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)
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.
def merge_sort(arr):
merge_sort is defined to take a single list arr as its parameter. if len(arr) > 1:
arr is greater than 1. If not, the array is already sorted (or empty), and the function returns immediately. mid = len(arr) // 2
arr is found using integer division. This will be used to split the array into two halves. L = arr[:mid]
R = arr[mid:]
arr is split into two halves: L (left half) and R (right half). merge_sort(L)
merge_sort(R)
L and the right half R. i = j = k = 0
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. 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 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. while i < len(L):
arr[k] = L[i]
i += 1
k += 1
L (if any). These elements are copied to arr. while j < len(R):
arr[k] = R[j]
j += 1
k += 1
R are copied to arr. return arr
arr is returned.arr = [12, 11, 13, 5, 6, 7]
sorted_arr = merge_sort(arr)
print("Sorted array is:", sorted_arr)
arr is sorted using the merge_sort function, and the sorted list is printed.