I have a big problem understanding complexity and especially with binary trees
.
For example, I know that when we have a problem, with say the problem's size is x=log2(sizeofarray)
but I don't understand where this log2
comes from?
I have a big problem understanding complexity and especially with binary trees
.
For example, I know that when we have a problem, with say the problem's size is x=log2(sizeofarray)
but I don't understand where this log2
comes from?
It's log2 because each level of tree splits your problem into two.
For instance, consider this set of data:
{ 1, 2, 3, 4, 5, 6, 7, 8 }
The first level could be
{ 1, 2, 3, 4 }, { 5, 6, 7, 8 }
the second level:
{ 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 }
the third level:
{ 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 }, { 7 }, { 8 }
Here with 8 values, log2(8) = 3, and there are 3 levels in the tree.
Also see these other StackOverflow questions for more:
Let's take a binary search as the easy example. Say you have a sorted list of 64 elements, and you're searching for a particular one. In each iteration, you halve the dataset. By the time your dataset has 1 element, you have halved it 6 times (count the arrows, not the numbers):
64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1
The reason for this is the fact that 64 = 2 ^ 6
, where 2
is the base (you divide the dataset in 2 parts in each iteration), and the exponent is 6
(as you get to the bottom in 6 iterations). There is another way to write this, since exponentiation has its inverse in logarithm:
64 = 2 ^ 6
6 = log2 64
So we can see that the number of iterations scales with the base-two logarithm of the number of elements.