繁体   English   中英

最大的未排序数字数组的以下时间复杂度

[英]Time complexity for the following for Largest in array of unsorted numbers

任何人都可以帮助分析这个罐的时间复杂度并解释原因。 我正在将数组元素相互比较,其中一个是最大值。 我不确定如何为此计算时间复杂度。 谁能帮我这个?

 class Largest
 {
     public static void main (String[] args) 
  {
    int array[] = {33,55,13,46,87,42,10,34};
    int max = array[0]; // Assume array[0] to be the max for time-being

    for( int i = 1; i < array.length; i++) // Iterate through the First Index and compare with max
    {
        if( max < array[i])
        {
            max = array[i];
        }
    }
    System.out.println("Largest is: "+ max);
 }
}

它是O(n)

//loop n-1 times, O(n)
for( int i = 1; i < array.length; i++) // Iterate through the First Index and compare with max
{
    //one comparison operation, O(1)
    if( max < array[i])
    {
        //one assignment operation, O(1)
        max = array[i];
    }
}

您执行 2 次常量操作,n-1 次。

O(n) * [O(1) + O(1)] = O(n)

你循环了n - 1次,所以复杂度是O(n)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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