-2

I want to analyze the execution time complexity of the below program. Please answer with the explanation.

private static void printSecondLargest(int[] arr) {
    int length = arr.length, temp;
    for (int i = 0; i < 2; i++) {
        for (int j = i+1; j < length; j++) {
            if(arr[i]<arr[j]) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    System.out.println("Second largest is: "+arr[1]);
}

4 Answers4

3

It's O(n) where n represents the length of the array.

The body of the inner most loop:

if(arr[i]<arr[j]) {
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

runs in constant time.

This code will be executed first arr.length-1 times, then arr.length-2 times. That is 2 * arr.length - 3. Thus the execution time is proportional to 2n-3 which is O(n).

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • How did you get 4n? Two executions = 2n? – aioobe Feb 18 '15 at 11:33
  • Thanks aioobe. Do u know any better approach to solve it in C? – Rahul Chaubey Feb 18 '15 at 11:39
  • You can't do better than O(n), but see for instance [this question](http://stackoverflow.com/questions/25490946/how-to-find-the-second-largest-element-using-c-program-without-using-array) for alternative implementatios. Also, please read [this](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – aioobe Feb 18 '15 at 11:41
  • 1
    @bigdestroyer, code won't execute (2*n -3) twice. it will n-1 first time and n-2 second time, so n-1 + n-2 = 2n-3 in total. – Rahul Chaubey Feb 18 '15 at 11:44
1

It is clearly O(n). The outer loop is running only 2 times and inner loop N times. So, overall complexity is O(2*n).

Ankita Singh
  • 107
  • 1
  • 5
0

The outer loop will run two times and inner loop runs (length-1) and second time (length-2)

suppose length is N

so it will be 2*((N-1)/2+(N-2/)2)==2*(2n-3)/2

Which is final (2N-3) and in O notation it is O(N)
squiroid
  • 13,809
  • 6
  • 47
  • 67
0
private static void printSecondLargest(int[] arr) {    
    int length = arr.length, temp;    // **it takes contant time**
    for (int i = 0; i < 2; i++) {     // as loop goes only two step it also takes constant time
        for (int j = i+1; j < length; j++) {   // this loop takes n time if we consider arr length of size n
            if(arr[i]<arr[j]) {
                temp = arr[i];    // it also takes constant time
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    System.out.println("Second largest is: "+arr[1]);
}

So as per above calculation we neglect constant time and calculate all varying time constraint and as per code complexity will be O(n).

Lrrr
  • 4,755
  • 5
  • 41
  • 63