My current challenge involves working with an alphabetically sorted array of strings:
let collection = ["ABC", "BCD", "CAB", "FGH", "JKL", "ZKL"];
The task at hand is to insert the string "CQW"
into the collection while maintaining the sorted order without having to re-sort the entire array.
My desired outcome is to have
["ABC", "BCD", "CAB", "CQW", "FGH", "JKL", "ZKL"];
after the insertion is completed in O(log n)
time.
To achieve this, I am considering leveraging binary search to calculate the index at which the new element should be inserted.
I came across a binary search code snippet that can find the index of a string within the collection:
function binarySearch(items, value) {
let startIndex = 0;
let stopIndex = items.length - 1;
let middle = Math.floor((stopIndex + startIndex) / 2);
while (items[middle] != value && startIndex < stopIndex) {
//adjust search area
if (value < items[middle]) {
stopIndex = middle - 1;
} else if (value > items[middle]) {
startIndex = middle + 1;
}
//recalculate middle
middle = Math.floor((stopIndex + startIndex) / 2);
}
// Return -1 if element is not in collection
return (items[middle] != value) ? -1 : middle;
}
let collection = ["ABC", "BCD", "CAB", "FGH", "JKL", "ZKL"];
console.log(binarySearch(collection, "CQW"));
However, I am facing a challenge in modifying the code to return the exact index for inserting the string. How can this code be adjusted to achieve that? Is binary search the most efficient approach for this task?