2

Can anyone help to analyze the time complexity of this can and please explain why. I'm comparing the array elements with each other with one being max. I'm not sure how to calculate the time complexity for this. Can anyone help me with this?

 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);
 }
}
  • Possible duplicate of [this](http://stackoverflow.com/questions/11032015/how-to-find-time-complexity-of-an-algorithm). – bcsb1001 Sep 01 '15 at 14:52

2 Answers2

1

It is 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];
    }
}

You do 2 constant operations, n-1 times.

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

James Wierzba
  • 16,176
  • 14
  • 79
  • 120
0

You loop goes around n - 1 times so the complexity is O(n)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130