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

35 lines (34 loc) 1.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mergeSort = mergeSort; function merge(left, right) { const result = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] <= right[rightIndex]) { result.push(left[leftIndex]); ++leftIndex; } else { result.push(right[rightIndex]); ++rightIndex; } } // console.log('Result:', result); // console.log('\tLeft:', left.slice(leftIndex)); // console.log('\tRight:', right.slice(rightIndex)); return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)); // Add remaining elements on either side } function mergeSort(inputArr) { if (inputArr.length === 1) return inputArr; // Base Case // Split Array in into right and left const middleIndex = Math.floor(inputArr.length / 2); const left = inputArr.slice(0, middleIndex); const right = inputArr.slice(middleIndex); // console.log('left:', left); // console.log('right:', right); return merge(mergeSort(left), mergeSort(right)); }