I'm working on finding the max pairwise product of an array algorithm as practice. I've been able to get it down to 2n comparisons, by finding the largest and second largest numbers in the array using two seperate for loops. I know i could get it down even farther if I sorted then compared.
In the algorithm below is it n comparisons? I only have 1 loop so I'm assuming it is. also, what would be the Big O number for this? Is it the same as the number of comparisons? I know that we remove any constants if there is a variable and take the largest degree of the problem [sorry for the unclear explanations of algorithms -I'm just beginning on this.
static int EvenFasterAlgorithm (int[] numbers) {
int maxNum1, maxNum2, index, index2;
maxNum1 = -1;
maxNum2 = -1;
index = -1;
index2 = -2;
System.out.println("the size is "+ numbers.length);
int k = numbers.length-1;
if(numbers.length > 1)
{
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] > maxNum1 && i != index2) {
maxNum1=numbers[i];
index = i;
}
if(numbers[k] >= maxNum2 && k != index)
{
maxNum2 = numbers[k];
index2 = k;
}
k--;
}
return maxNum1*maxNum2;
}
else
{
return numbers[0];
}
}