UNPKG

sorting-algorithms-lib

Version:

sorting-algorithms-lib is a lightweight JavaScript library that provides efficient implementations of various sorting algorithms. Whether you're learning algorithms, benchmarking performance, or building a project that requires sorting, this library has y

52 lines (51 loc) 1.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.insertionSort = insertionSort; function insertionSort(inputArr) { if (typeof inputArr[0] === 'number') { let arr = inputArr; for (let i = 0; i < inputArr.length; ++i) { if (arr[i] < arr[0]) { const element = arr.splice(i, 1); // Move element to the first position arr.unshift(element[0]); } else { // Only sort number smaller than preceding number if (arr[i] < arr[i - 1]) { // Find where element's sorted position for (var j = 1; j < i; j++) { if (arr[i] >= arr[j - 1] && arr[i] < arr[j]) { // Move element to the sorted spot arr.splice(j, 0, arr.splice(i, 1)[0]); } } } } } return arr; } else if (typeof inputArr[0] === 'string') { let arr = inputArr; for (let i = 0; i < inputArr.length; ++i) { if (arr[i] < arr[0]) { const element = arr.splice(i, 1); // Move element to the first position arr.unshift(element[0]); } else { // Only sort number smaller than preceding number if (arr[i] < arr[i - 1]) { // Find where element's sorted position for (var j = 1; j < i; j++) { if (arr[i] >= arr[j - 1] && arr[i] < arr[j]) { // Move element to the sorted spot arr.splice(j, 0, arr.splice(i, 1)[0]); } } } } } return arr; } }