Nested for loop in Big Oh Complexity

后端 未结 3 623
南方客
南方客 2021-01-21 10:17
for(int i = 0; i < n; i++) {
    for(int j = 0; j < i; j++){
        //do swap stuff, constant time
    }
}

I read that single for loop is O(N) a

3条回答
  •  再見小時候
    2021-01-21 11:01

    A function that loops from i = 1 to n and then has a inner loop that goes from 1 to i would go though a number of iteration equal to this formula:

    n(n+1)/2

    As you can see, when we get rid of everything besides the main exponent, you end with O(n^2)

提交回复
热议问题