Sort an array using the merge sort algorithm with O(n log n) time complexity.
Code
Algorithmsconst merge = (l, r) => {
const result = [];
while (l.length && r.length) result.push(l[0] <= r[0] ? l.shift() : r.shift());
return [...result, ...l, ...r];
};
const mergeSort = a => a.length <= 1 ? a : merge(
mergeSort(a.slice(0, Math.floor(a.length / 2))),
mergeSort(a.slice(Math.floor(a.length / 2)))
);
return mergeSort(arr);Parameters
Array to sort
Browser·fetch() may be limited by CORS
More JavaScript Snippets
Bubble Sort
Sort an array using the bubble sort algorithm by repeatedly swapping adjacent elements.
Counting Sort
Sort an array of non-negative integers using counting sort for linear time performance.
Heap Sort
Sort an array using the heap sort algorithm with O(n log n) time complexity.
Insertion Sort
Sort an array using the insertion sort algorithm by building a sorted portion one element at a time.
Quicksort
Sort an array using the quicksort algorithm with average O(n log n) time complexity.
Selection Sort
Sort an array using the selection sort algorithm by repeatedly finding the minimum element.