Why is Binary Search a divide and conquer algorithm?

后端 未结 16 2335
醉话见心
醉话见心 2020-12-14 02:12

I was asked if a Binary Search is a divide and conquer algorithm at an exam. My answer was yes, because you divided the problem into smaller subproblems, until you reached y

16条回答
  •  感动是毒
    2020-12-14 02:42

    Binary search is tricky to describe with divide-and-conquer because the conquering step is not explicit. The result of the algorithm is the index of the needle in the haystack, and a pure D&C implementation would return the index of the needle in the smallest haystack (0 in the one-element list) and then recursively add the offsets in the larger haystacks that were divided in the divison step.

    Pseudocode to explain:

    function binary_search has arguments needle and haystack and returns index
        if haystack has size 1
           return 0
        else 
            divide haystack into upper and lower half
            if needle is smaller than smallest element of upper half
                return 0 + binary_search needle, lower half
            else
                return size of lower half + binary_search needle, upper half
    

    The addition (0 + or size of lower half) is the conquer part. Most people skip it by providing indices into a larger list as arguments, and thus it is often not readily available.

提交回复
热议问题