⬅ Previous Topic
Insertion SortNext Topic ⮕
Quick Sort⬅ Previous Topic
Insertion SortNext Topic ⮕
Quick SortTopic Contents
Given an array of integers, your task is to sort the array in ascending order using the Merge Sort algorithm.
Merge Sort is a divide and conquer algorithm. It divides the array into halves, recursively sorts them, and then merges the sorted halves into one final sorted array.
This algorithm is stable and guarantees a worst-case time complexity of O(n log n)
.
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
if __name__ == '__main__':
arr = [6, 3, 8, 2, 7, 4]
sorted_arr = merge_sort(arr)
print("Sorted array is:", sorted_arr)
⬅ Previous Topic
Insertion SortNext Topic ⮕
Quick SortYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.