Sort an array using the insertion sort algorithm by building a sorted portion one element at a time.
Code
Algorithmsconst a = [...arr];
for (let i = 1; i < a.length; i++) {
const key = a[i];
let j = i - 1;
while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
a[j + 1] = key;
}
return a;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.
Merge Sort
Sort an array using the merge sort algorithm with O(n log n) time complexity.
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.