trekhleb / javascript-algorithms

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings
MIT License
184.97k stars 29.83k forks source link

Unhandled Edge Case in Binary Search Implementation #1095

Open ShadBalti opened 6 months ago

ShadBalti commented 6 months ago

The current implementation of the binary search algorithm in the JavaScript codebase does not handle a specific edge case where the target element is present multiple times in the sorted array. This issue is reported to address the potential misbehavior and propose a solution to handle scenarios where the binary search encounters duplicate elements.

Steps to Reproduce:

  1. Input a sorted array containing duplicate elements.
  2. Perform a binary search for a target element present multiple times in the array.
  3. Observe the behavior when the target element is found.

Expected Behavior: The binary search algorithm should reliably locate and return any occurrence of the target element in the sorted array, providing accurate indices for all instances.

Current Behavior: The current implementation may not consistently handle scenarios where duplicate elements exist in the sorted array, leading to unpredictable results when searching for the target element.

faresh9 commented 5 months ago

The claim is partially true. The current implementation of the binary search algorithm in the JavaScript code does not explicitly handle the case where the target element is present multiple times in the sorted array. The algorithm will find the index of the target element if it exists in the array, but it does not specify which occurrence of the element it will return.

In the code snippet:

if (comparator.equal(sortedArray[middleIndex], seekElement)) {
  return middleIndex;
}

If the target element is present multiple times, this condition will return the index of any occurrence of the element found during the search. It doesn't guarantee that it will return the first, last, or any specific occurrence of the element.

If handling duplicate elements in a specific way (e.g., returning the index of the first occurrence) is important for your use case, you might need to modify the binary search implementation accordingly. You could consider additional logic to determine how to handle duplicate elements based on your requirements.

So, while the claim is true in the sense that the provided implementation doesn't explicitly address the handling of duplicate elements, the behavior might still be acceptable depending on the context in which the binary search is used.