I have a program that finds the two largest elements of an Array. I have to look at the number of comparisons between elements of the Array to determine efficiency (not big-O) I have determined the worst-case is 2n-3 comparisons (assuming the first two elements are the largest) Here is the function.
Integer[] A = {11,22,8,7,5,6,7,8,1,9};
int largest = 0;
int secondLargest = 0;
int count = 1;
if (A[0] < A[1]){
largest = A[1];
secondLargest = A[0];
} else {
largest = A[0];
secondLargest = A[1];
}
for (int i = 2; i < A.length; i++){
count++;
if (A[i] > largest) {
secondLargest = largest;
largest = A[i];
} else {
count++;
if (A[i] > secondLargest) {
secondLargest = A[i];
}
}
}
System.out.println("Largest:" + largest + " Second:" + secondLargest + " count:" + count);
I use count to determine the number of comparisons. Is there any way to reduce the number of worst case comparisons within this function? I can't figure out how to make this function better.