简体   繁体   中英

Time complexity analysis in finding index of smallest element in an array-worst,average and best case

int j = 0;
for(int i = 0; i < n; ++i) {
    while(j < n && arr[i] < arr[j]) {
        j++;
    }
}

Here is a code for finding index of smallest element (first occurrence) in an array.And i say that the worst case would be O(n2) best case would be O(n).

Question 1: In the worst case my inner while loop does not always runs for n times,in maximum of cases it would run for 1 or 2 times with respect to outer for loop,So i assume that the inner loop runs for (nc) times where c is some constant and outer loop runs for n times.Am i correct that the complexity would we n*(nc) which is O(n2) ?

In the best case minimum element being at first index,my inner loop does not runs any time so the time complexity is O(n).

Question 2: How can i derive average case?

You start with j = 0 and never decrement j . Each iteration of the while loop increases j by one, and the while loop has the condition j < n , so the statement j++ can run at most n times, ie worst case O(n).

We can simply ignore constant while finding the Big O notation( why? ).

The program you wrote for finding index of minimum element in the array makes n iterations when array elements are in increasing order and 2*n iterations when array elements are in decreasing order. But we can simply conclude that this algorithm has overall O(n) complexity in all three cases.

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