Hi guys,
so I'm studying time complexities of algorithms, I'm having some confusion with logarithms.
I understand what a logarithm is, let's say 2^3 = 8, so log 2(8) = 2^x = 8 which equals 3, so log 2(8) = 3,
or another way to think of it we have 8 how many times can we divide 8 by half until we reach 1, 8 -> 4 -> 2 - > 1 = 3 times
but using logarithms with algorithms kind of confuses me.
we have a binary tree with 7 items
1 2 3 4 5 6 7
|
X
/ \
X X
/\ / \
X X X X
|
so log(7) gives us 2, but this is wrong as we need log(n+1) which would be 8, so why we do we the number of nodes+1 to get the number of levels?
secondly why isn't it log(4)? for example if we had a function to find out how many levels of work a recursive algorithm would do on an array, let's say we have an array [1,2,3,4,5,6,7,8]
we would do log(8) to find the levels of work right?? ( why is it different with the binary tree? why do we use the number of nodes+1 and with the array algorithm we use the number of elements?
let me try draw an example it may explain it a little better
1 2 3 4 5 6 7 8 9
|
[1,2,3,4,5,6,7,8]
/ \
[1,2,3,4] [5,6,7,8]
/ \ \ /
[1,2] [3,4] [5,6] [7,8]
/ \ / \ / \ / \
[1][2][3][4] [5][6][7][8]
|
if we count an element as each [] then we have 15 [] , 1 in the first,2 in the second,4 in the third, 8 in the last, so log(15+1) = log(16) = 4
this gives us 4 levels of work, but if we do log(8) we get 3 levels, so which one is correct? and how come we use log(n+1) in a binary tree and log(num of elements in array) in finding levels of work? and lastly why log(n+1) but not log(num of elements in array+1)?
* log base 2 is implied in this question
thanks