JavaScript Merge Sort
Merge Sort is basically a divide and conquer algorithm. It consists of 2 parts:
- Sorting Part
- If array length is 1 then return original array
- Divide array into 2 equal parts (where possible) and recursively sort them
- Merge sorted parts
- Merge Part
- Merge 2 arrays by taking lowest element from arrays' heads
Merge function splits array recursively until there is only 1 element left in each subarray and then merges sorted pairs of subarrays:
Merge function merges 2 sorted arrays and returns a sorted array: