2

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

Manan Kalra
  • 41
  • 1
  • 4
  • 1
    possible duplicate of [Why use binary search if there's ternary search?](http://stackoverflow.com/questions/3498382/why-use-binary-search-if-theres-ternary-search) – orlp Sep 14 '15 at 19:33
  • 1
    This really depends on what you are trying to do, what are you trying to do? – Clarus Sep 14 '15 at 19:33

2 Answers2

5

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.

Louis Ricci
  • 19,594
  • 5
  • 43
  • 60
0

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.

user448810
  • 16,364
  • 2
  • 31
  • 53