Binary Search vs Ternary Search

跟風遠走 提交于 2019-12-11 03:24:48

问题


In terms of time and space complexity, is binary search better than ternary search?


回答1:


Both have constant space, but big O time for Ternary Search is Log_3 N instead of Binary Search's Log_2 N which both come out to log(N) since log_b(N) = log_x(N)/log_x(b).

In practice Ternary Search isn't used because you have to do an extra comparison at each step, which in the general case leads to more comparisons overall. 2 * Log_3(N) comparisons vs Log_2(N) comparisons.




回答2:


It probably depends on the data. If you have roughly equal numbers of less than, equal to, and greater than comparisons, then splitting the data three ways means the base of the logarithm is 3 rather than 2, which is better. But in practice a three-way comparison is more expensive than a 2-way comparison, so the extra cost of the three-way comparison probably isn't worth it in the general case.



来源:https://stackoverflow.com/questions/32572355/binary-search-vs-ternary-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!