简体   繁体   中英

Time complexity or Big O of the code

I have this array which has a max heap property. The time complexity of deleteMax is O(logn). If the code below will iterate for only 7 times, what would be the time complexity of the below code (big O)?

int heap_size = 15;
int i, value, heap_array[]; // array is in the form of max heap
....
for(i = 0; i < 7; i++){ // iterates seven times
    value = deleteMax(heap_array);
    printf("%d ", value);
}

I have two solutions in my mind. First: The time complexity is O(7 * logn) or simply O(logn).

Then the second one is O(1/2 * n * logn) or O(nlogn) since 1/2 is just a constant and I'm assuming that since the number of iteration is 7 which is almost the same as the half the heap_size, I can disregard 1/2. Thus O(nlogn)

Which one would be correct?

In general it is pointless to talk about complexity when a number is fixed (aka constant). The whole purpose of the notation is to evaluate how execution time changes when a number changes. A constant number of loops will never change execution time nor complexity. If you change the number of loops to another constant value, it will change execution time but complexity is the same.

The typical use is to calculate the complexity of a function in order to give the user of the function an idea about how execution time changes when the user changes some input value. Example:

void foo()                 // Pointless to talk about complexity as there is no input

void foo(int x)            // Complexity tells you how execution time change 
                           // when you change x

void foo(char* someString) // Complexity tells you how execution time change 
                           // when you change the length of someString

Note: Complexity never tells you the actual execution time! Only how execution time changes when some input is changed.

So in your case, it is still deleteMax that determines complexity, ie it is still O(log n). Simply because there is no input changing the number of loops.

If the loop only runs 7 times then the complexity is O(1). This is for the reason that the loop does not depend on the size of the data and will always run in constant time.

Here, both the heap size and number of times the loop runs are constant. So the code will have a time complexity of O(1), ie, constant time complexity.

我认为你倾向于堆排序算法,我确信复杂性是O(nlogn)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM