First and last occurrence for binary search in C

前端 未结 5 904
旧时难觅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 01:07

    Just perform a normal binary search for the element (e). Let's say it returns index i. To find the index of the first occurrence just do a binary search for e on [0<->i-1] repeatedly until the search can't find e anymore. Similarly do [i+1<->n] for last occurrence.

提交回复
热议问题