Menu

gitpiper

insertionSort javascript Code Snippet in 2024

algorithmarrayintermediate

Last Updated: 6 June 2024

Sorts an array of numbers, using the insertion sort algorithm.

  • Use Array.prototype.reduce() to iterate over all the elements in the given array.
  • If the length of the accumulator is 0, add the current element to it.
  • Use Array.prototype.some() to iterate over the results in the accumulator until the correct position is found.
  • Use Array.prototype.splice() to insert the current element into the accumulator.
const insertionSort = arr => arr.reduce((acc, x) => { if (!acc.length) return [x]; acc.some((y, j) => { if (x <= y) { acc.splice(j, 0, x); return true; } if (x > y && j === acc.length - 1) { acc.splice(j + 1, 0, x); return true; } return false; }); return acc; }, []);
insertionSort([6, 3, 4, 1]); // [1, 3, 4, 6]

javascript snippet similar to insertionSort For You in June 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️