Back to list

Merge Sort

Divides the array into two halves, recursively sorts them, and then merges the sorted halves.

Start: Unsorted ArrayItems: 8
24
14
86
18
89
63
84
54
Speed
Comp
0
Writes
0
Array Controls

Time Complexity

Best
O(n log n)
Avg
O(n log n)
Worst
O(n log n)

Space Complexity

Auxiliary SpaceO(n)

Algorithm Details

Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.

How it works

  1. Divide: Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted).
  2. Conquer: Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list.

Complexity

  • Time Complexity: O(n log n) in all 3 cases (worst, average and best) as merge sort always divides the array into two halves and takes linear time to merge two halves.
  • Space Complexity: O(n)

Implementation

1def merge_sort(arr):
2  if len(arr) > 1:
3      mid = len(arr)//2
4      L = arr[:mid]
5      R = arr[mid:]
6
7      merge_sort(L)
8      merge_sort(R)
9
10      i = j = k = 0
11
12      # Copy data to temp arrays L[] and R[]
13      while i < len(L) and j < len(R):
14          if L[i] < R[j]:
15              arr[k] = L[i]
16              i += 1
17          else:
18              arr[k] = R[j]
19              j += 1
20          k += 1
21
22      # Checking if any element was left
23      while i < len(L):
24          arr[k] = L[i]
25          i += 1
26          k += 1
27
28      while j < len(R):
29          arr[k] = R[j]
30          j += 1
31          k += 1
32
33# Example usage
34arr = [12, 11, 13, 5, 6, 7]
35merge_sort(arr)
36print("Sorted array is:", arr)