Why use binary search if there's ternary search?

前端 未结 15 1676
别跟我提以往
别跟我提以往 2020-12-02 12:43

I recently heard about ternary search in which we divide an array into 3 parts and compare. Here there will be two comparisons but it reduces the array to n/3. Why don\'t p

15条回答
  •  执笔经年
    2020-12-02 12:55

    "Terinary" (ternary?) search is more efficient in the best case, which would involve searching for the first element (or perhaps the last, depending on which comparison you do first). For elements farther from the end you're checking first, while two comparisons would narrow the array by 2/3 each time, the same two comparisons with binary search would narrow the search space by 3/4.

    Add to that, binary search is simpler. You just compare and get one half or the other, rather than compare, if less than get the first third, else compare, if less than get the second third, else get the last third.

提交回复
热议问题