DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question
  1. Home
  2. Tools
  3. Algorithm Visualizer
  4. Merge Sort

Merge Sort

Sortingmedium#4

Divide array in half, sort each half, then merge them back

Ready

Step 1 of 0

Speed

Input Data

Comma-separated numbers (0-999). Min 2 values.

Algorithm Code

1function mergeSort(arr, l, r) {
2 if (l >= r) return;
3 const mid = Math.floor((l + r) / 2);
4 mergeSort(arr, l, mid);
5 mergeSort(arr, mid + 1, r);
6 merge(arr, l, mid, r);
7}
8function merge(arr, l, mid, r) {
9 const L = arr.slice(l, mid + 1);
10 const R = arr.slice(mid + 1, r + 1);
11 let i = 0, j = 0, k = l;
12 while (i < L.length && j < R.length) {
13 if (L[i] <= R[j]) arr[k++] = L[i++];
14 else arr[k++] = R[j++];
15 }
16 while (i < L.length) arr[k++] = L[i++];
17 while (j < R.length) arr[k++] = R[j++];
18}
Best

O(n log n)

Average

O(n log n)

Worst

O(n log n)

Space

O(n)

About Merge Sort

Merge Sort is a divide-and-conquer algorithm that divides the array into halves, recursively sorts each half, then merges them back together. It guarantees O(n log n) time complexity but requires O(n) extra space.

Time Complexity: Best: O(n log n), Average: O(n log n), Worst: O(n log n). Space: O(n).

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.