Tuesday, October 2, 2018

Complexity of Algorithms - Why O (Logn) ?

n = 8
|1|2|3|4|5|6|7|8|                                -  I have n  elements in yellow color
n/21                                                  -  I divide n in half (by 2)
|1|2|3|4|        |5|6|7|8|                       -  Now I have n/2
n/22                                                  I divide n/2 in half (by 2)
|1|2|   |3|4|      |5|6|      7|8|                -  Now I have n/22 
n/23                                                 -  I divide n/22  in half (by 2) 2
|1|  |2|   |3|   |4|  |5|  |6|   |7|    |8|     -  Now I have n/23  =  1  element in yellow color

I divided by 2, 3 times that is the number of interaction in a loop or recursion of our algorithm
but if n was bigger or shorter we would generically divide it by x

x = number of interactions or division of our problem in the half
n /(2x) = 1     - after x divisions we have only 1  left
n = 2x          - we apply logarithm in base 2 in both sides
log2n = log22x  
log2n = xlog2log22 = 1
log2n = x       - from here we get that the number of interactions is log2n or simple log n


No comments:

Blog Archive