First and last occurrence for binary search in C

前端 未结 5 902
旧时难觅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:57

    You could run binary search to find any arbitrary occurrence (if it exists) of the key in the array.

    Next, the first occurrence would be to the left of the index returned, so you set the bounds accordingly and run binary search repeatedly until the element to the left of the index is not equal to the key. Proceed similarly for the last occurrence

    binary_search(0, n-1, key)
    {
        /* run binary search, get index of key */
        leftmost=min(leftmost, index)
        if (array[index-1]==key and leftmost==index)
            binary_search(0, index-1, key)
        rightmost=max(rightmost, index)
        if (array[index+1]==key and rightmost==index)
            binary_search(index+1, n-1, key)
    }
    

提交回复
热议问题