Big O - O(log(n)) code example

后端 未结 7 1258
予麋鹿
予麋鹿 2020-12-23 12:37

Like the Big O notation \"O(1)\" can describe following code:

O(1):

    for (int i = 0; i < 10; i++) {
        // do stuff 
        a[i] = INT;
    }

O         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 12:41

    From definition, log(n) (I mean here log with base 2, but the base really doesn't matter), is the number of times, that you have to multiply 2 by itself to get n. So, O(log(n)) code example is:

    i = 1
    while(i < n)
        i = i * 2
        // maybe doing addition O(1) code
    

    In real code examples, you can meet O(log(n)) in binary search, balanced binary search trees, many resursive algoritmhs, priority queues.

提交回复
热议问题