- 350
- 203
Binary search works by eliminating half of the objects in a sorted array every time,so shouldn’t it’s time complexity being ##O(\log_2 n)## instead of ##O(\log n)##?
The time complexity of binary search is correctly represented as O(log n), which is equivalent to O(log₂ n) due to the properties of logarithms. The difference between logarithmic bases becomes negligible as input size increases, and constants are disregarded in Big O notation. In computer science, log(n) typically refers to log base 2, while in other fields, such as mathematics, it may refer to natural logarithm (ln) or common logarithm (log₁₀). This distinction is important for clarity but does not affect the overall time complexity classification.
PREREQUISITESComputer scientists, software engineers, and students studying algorithms who seek to deepen their understanding of time complexity and logarithmic functions.
I do get that when the input tends to infinity,the difference between ##\log x## and ##\log_2 x## becomes smaller and smaller,but why don’t they just use ##O(\log_2 x)##?mfb said:Where is the difference?
It isn't about limits as n tends to infinity. Do you know how to express the ##\log_b x##, where ##b## is any base, in terms of ##\log x##?Young physicist said:I do get that when the input tends to infinity,the difference between ##\log x## and ##\log_2 x## becomes smaller and smaller,but why don’t they just use ##O(\log_2 x)##?
Yes, I do.Ibix said:Do you know how to express the logbxlogbx\log_b x, where bbb is any base, in terms of logxlogx\log x?
Ohh~~problem solved!mfb said:So ln(x) and log2 only differ by a constant (ln(2)). A constant doesn't matter. ##O(\log n) = O(5\log n) = O(46342\log n)##
It doesn't matter. All bases do the same thing - you just multiply by a constant to change base, and you discard that constant in this case.Young physicist said:Ohh~~problem solved!
Edit:so this ##\log x## means ##\log_e x## rather than ##\log_{10} x## ?
Yeah.Just making sure the ln(x) posted by @mfb isn’t an accident.Ibix said:It doesn't matter. All bases do the same thing - you just multiply by a constant to change base, and you discard that constant in this case.
In computer science books ##\log(n)## is usually taken to mean ##\log_2(n)##.Young physicist said:Binary search works by eliminating half of the objects in a sorted array every time,so shouldn’t it’s time complexity being ##O(\log_2 n)## instead of ##O(\log n)##?
woah!mfb said:Computer science read log(x) as base 2, mathematics and most of physics will see it as base e, chemistry will see it as base 10, ...