Skip to content

Fix binary search to return leftmost occurrence for duplicates - #13891

Merged
cclauss merged 2 commits into
TheAlgorithms:masterfrom
CommitToday:fix-issue-13887-add-missing-shell-sort-algorithm
Sep 15, 2026
Merged

cclauss merged 2 commits into
TheAlgorithms:masterfrom
CommitToday:fix-issue-13887-add-missing-shell-sort-algorithm

Conversation

@CommitToday

@CommitToday CommitToday commented Nov 10, 2025

Copy link
Copy Markdown
Contributor

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

Fixes #13841
Fixes #13887
Fixes #13901
Fixes #13955
Fixes #14051
Fixes #14456
Fixes #14622
Fixes #14708

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
@algorithms-keeper algorithms-keeper Bot removed the awaiting reviews This PR is ready to be reviewed label Sep 15, 2026
@cclauss
cclauss merged commit 1d46ea5 into TheAlgorithms:master Sep 15, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

2 participants