|
| 1 | +'use strict'; |
| 2 | +Object.defineProperty(exports, '__esModule', { value: true }); |
| 3 | +exports.insertIntoSortedArray = void 0; |
| 4 | +/** |
| 5 | + * Inserts an element into a sorted array. |
| 6 | + * @template T |
| 7 | + * @param {Array<T>} array - The sorted array to insert into. |
| 8 | + * @param {T} element - The element to insert. |
| 9 | + * @param {(a: T, b: T) => number} compare - The comparison function used to sort the array. |
| 10 | + * @returns {number} The index at which the element was inserted. |
| 11 | + */ |
| 12 | +function insertIntoSortedArray(array, element, compare) { |
| 13 | + let high = array.length - 1; |
| 14 | + let low = 0; |
| 15 | + let mid; |
| 16 | + let highElement, lowElement, midElement; |
| 17 | + let compareHigh, compareLow, compareMid; |
| 18 | + let targetIndex; |
| 19 | + while (targetIndex === undefined) { |
| 20 | + if (high < low) { |
| 21 | + targetIndex = low; |
| 22 | + continue; |
| 23 | + } |
| 24 | + mid = Math.floor((low + high) / 2); |
| 25 | + highElement = array[high]; |
| 26 | + lowElement = array[low]; |
| 27 | + midElement = array[mid]; |
| 28 | + compareHigh = compare(element, highElement); |
| 29 | + compareLow = compare(element, lowElement); |
| 30 | + compareMid = compare(element, midElement); |
| 31 | + if (low === high) { |
| 32 | + // Target index is either to the left or right of element at low |
| 33 | + if (compareLow <= 0) targetIndex = low; |
| 34 | + else targetIndex = low + 1; |
| 35 | + continue; |
| 36 | + } |
| 37 | + if (compareHigh >= 0) { |
| 38 | + // Target index is to the right of high |
| 39 | + low = high; |
| 40 | + continue; |
| 41 | + } |
| 42 | + if (compareLow <= 0) { |
| 43 | + // Target index is to the left of low |
| 44 | + high = low; |
| 45 | + continue; |
| 46 | + } |
| 47 | + if (compareMid <= 0) { |
| 48 | + // Target index is to the left of mid |
| 49 | + high = mid; |
| 50 | + continue; |
| 51 | + } |
| 52 | + // Target index is to the right of mid |
| 53 | + low = mid + 1; |
| 54 | + } |
| 55 | + array.splice(targetIndex, 0, element); |
| 56 | + return targetIndex; |
| 57 | +} |
| 58 | +exports.insertIntoSortedArray = insertIntoSortedArray; |
0 commit comments