Skip to content

Conversation

@SoulSniper1212
Copy link

Overview
This PR fixes issue #13887 by modifying the binary search implementation to return the index of the leftmost occurrence when there are multiple occurrences of the search item in the sorted collection. Previously, the function would return any arbitrary occurrence.

Checklist

  • Code changes implemented in both iterative and recursive binary search functions
  • Added test cases to verify the new behavior
  • Updated docstrings to reflect the new behavior

Proof
The changes include:

  1. Modified the iterative binary_search function to continue searching to the left after finding a match to locate the leftmost occurrence
  2. Rewrote the recursive binary_search_by_recursion function with an inner helper function that properly handles finding the leftmost occurrence
  3. Added specific test cases like binary_search([1, 2, 4, 4, 4, 6, 7], 4) which should return 2 (the index of the leftmost occurrence of 4)
  4. Updated docstrings to clearly document that the function returns the leftmost occurrence when duplicates exist

Closes #13887

Signed-off-by: SoulSniper1212 <warush23@gmail.com>
@algorithms-keeper algorithms-keeper bot added enhancement This PR modified some existing files awaiting reviews This PR is ready to be reviewed labels Nov 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add missing Shell Sort algorithm

1 participant