Merge Sort Visualization

Speed:
Step: 0 / -1
Algorithm Code
1function mergeSort(arr) {
2    // Base case
3    if (arr.length <= 1) {
4      return arr;
5    }
6    
7    // Split array in half
8    const middle = Math.floor(arr.length / 2);
9    const left = arr.slice(0, middle);
10    const right = arr.slice(middle);
11    
12    // Recursively sort both halves
13    return merge(
14      mergeSort(left),
15      mergeSort(right)
16    );
17  }
18  
19  function merge(left, right) {
20    let result = [];
21    let leftIndex = 0;
22    let rightIndex = 0;
23    
24    // Compare elements and merge
25    while (leftIndex < left.length && rightIndex < right.length) {
26      if (left[leftIndex] < right[rightIndex]) {
27        result.push(left[leftIndex]);
28        leftIndex++;
29      } else {
30        result.push(right[rightIndex]);
31        rightIndex++;
32      }
33    }
34    
35    // Add remaining elements
36    return result
37      .concat(left.slice(leftIndex))
38      .concat(right.slice(rightIndex));
39  }
Visualization