[英]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). 这是一个用于查找数组中最小元素(第一次出现)的索引的代码。我说最坏的情况是O(n2)最好的情况是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) ? 问题1:在最坏的情况下,我的内部while循环并不总是运行n次,在最多的情况下,它将相对于外部for循环运行1或2次,所以我假设内部循环运行(nc)其中c是一些常数而外部循环运行n次。我正确的是复杂性我们n *(nc)是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). 在最好的情况下,最小元素在第一个索引处,我的内部循环不会在任何时间运行,因此时间复杂度为O(n)。
Question 2: How can i derive average case? 问题2:我如何得出平均情况?
You start with j = 0
and never decrement j
. 你从j = 0
开始,永远不会减少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). while
循环的每次迭代都将j
增加1,而while
循环的条件j < n
,因此语句j++
最多可运行n
次,即最坏情况为O(n)。
We can simply ignore constant while finding the Big O notation( why? ). 我们可以在找到Big O表示法时忽略常量( 为什么? )。
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. 您编写的用于查找数组中最小元素索引的程序在数组元素按递增顺序时进行n次迭代,在数组元素按递减顺序时进行2 * n次迭代。 But we can simply conclude that this algorithm has overall O(n) complexity in all three cases. 但我们可以简单地得出结论,该算法在所有三种情况下都具有总体O(n)复杂度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.