Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

Explain merge sort — divide, conquer, merge. Complexity?

FresherFundamentalsData Structures & Algorithms
Model answer

Merge sort

Divide array in half, sort halves recursively, merge sorted halves—O(n log n) time, O(n) auxiliary space. Stable.

diagram
split → sort left, sort right → merge two sorted lists
java
void merge(int[] a, int l, int m, int r) {
  int[] tmp = new int[r - l + 1];
  int i = l, j = m + 1, k = 0;
  while (i <= m && j <= r) tmp[k++] = a[i] <= a[j] ? a[i++] : a[j++];
  while (i <= m) tmp[k++] = a[i++];
  while (j <= r) tmp[k++] = a[j++];
  for (int t = 0; t < tmp.length; t++) a[l + t] = tmp[t];
}
Used for external sorting (data on disk) and parallel merge.