Insertion Sort

    0

    0

    Giovanny Gongora

    Codiga's TypeScript Recipes

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

    const insertionSort = (arr: number[]) =>
      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;
      }, []);
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.