Will this code run for all cases?

I thought of a more efficient way to solve this problem but I am unsure if it will work for all the cases. It will reduce the number of comparisons so it is more efficient. Please check:-

:

int largest=a[0];

int smallest=a[0];

for (i=1; i<=n-1; i++) {

    if (a[i] > largest)
           largest=a[i];
   else if (a[i]<smallest)
           smallest=a[i];

}

:

Since I have replaced one if with else if it would reduce the number of comparisons and make the code more efficient. Please tell.

Yes this will work fine.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.