Implement a function that performs an insertion sort. The function should take in an array of integers and return an array with the integers sorted in ascending order. The input array is modified.

insertionSort([9, 3, 6, 2, 1, 11]); // [1, 2, 3, 6, 9, 11]insertionSort([12, 16, 14, 1, 2, 3]); // [1, 2, 3, 12, 14, 16]
Insertion sort is a stable, in-place, comparison-based algorithm that works well for small to medium-sized arrays as well as arrays that are partially sorted.
It only requires a constant amount of work to sort an array that is already partially sorted.
If unspecified:
Note: This question tackles in-place sorting for an output in ascending order. Refer to the 'Notes' section below on how to handle other cases.
/*** @param {Array<number>} arr The input integer array to be sorted.* @return {Array<number>}*/export default function insertionSort(arr) {// Iterate through the array, starting with the 2nd element.for (let i = 1; i < arr.length; i++) {// Store the current value in a variable so it// can be shifted to the correct position after the comparisons.let currentValue = arr[i];// Initialize a pointer for the index of the previous element// so we can use it to iterate progressively backwards// through preceding elements.let j = i - 1;// Keep iterating backwards through preceding elements// as long as the previous element is greater than the current value.while (j >= 0 && arr[j] > currentValue) {// "Move" the previous element one position to the right.// if it's bigger than currentValue.arr[j + 1] = arr[j];// Decrement the pointer so as to keep comparing with the// previous element.j--;}// Set the currentValue into its final position.arr[j + 1] = currentValue;}// Return the sorted array.return arr;}
< instead of >, as per below:while (j >= 0 && arr[j] < currentValue)
Array.prototype.slice() to clone the input array and do the sorting on the cloned array instead.Let's analyze the algorithm's time and space complexity.
In the case of insertion sort, the best case time complexity is O(n), the worst case time complexity is O(n2), and the average case time complexity is also O(n2).
Due to the nested loop structure required in insertion sort where we have an outer loop that iterates over the array and inner loop which iterates over the already sorted array to find the correct position to insert the current element, the time complexity will generally be O(n2) if both loops iterate fully. The discrepancy between different cases is affected by how well sorted the original input is, which affects if we need to run the inner loop at all for specific elements.
The space complexity for insertion sort is O(1), as it does in-place sorting and does not require additional storage proportional to input size.
console.log() statements will appear here.