First and last occurrence for binary search in C

前端 未结 5 900
旧时难觅i
旧时难觅i 2021-01-06 00:46

I\'m trying to understand how do I modify the binary search for it work for first and last occurrences, surely I can find some code on the web but I\'m trying to reach deep

5条回答
  •  离开以前
    2021-01-06 00:58

    To my understanding, if the element you are looking for is found, one option would be to perform a linear search either to the left or right to find the first on last occurence.

    Alternatively, you could use binary search again to adap the position until the element at the next position changes. This could be done by modifying the middle case above; if the element is found, don't return its position until the position remains the same.

提交回复
热议问题