This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
42. implement Insertion Sort

function insertionSort(arr) { for (let i = 1; i < arr.length; i++) { const value = arr[i]; let j; for (j = i - 1; j >= 0 && arr[j] > value; j--) { arr[j + 1] = arr[j]; } arr[j + 1] = value; } }

// Test case const arr = [3, 2, 1, 5, 4]; insertionSort(arr); console.log(arr); // [1, 2, 3, 4, 5]

// Time complexity: // Average case: O(n^2) // Worst case: O(n^2) // The algorithm is stable.