Why use binary search if there's ternary search?

前端 未结 15 1707
别跟我提以往
别跟我提以往 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 13:04

    You may have heard ternary search being used in those riddles that involve weighing things on scales. Those scales can return 3 answers: left is lighter, both are the same, or left is heavier. So in a ternary search, it only takes 1 comparison. However, computers use boolean logic, which only has 2 answers. To do the ternary search, you'd actually have to do 2 comparisons instead of 1. I guess there are some cases where this is still faster as earlier posters mentioned, but you can see that ternary search isn't always better, and it's more confusing and less natural to implement on a computer.

提交回复
热议问题