Trying to do Big O analysis-
What is the average case for this program?. O(n/2(n/2)) = O(n^2) ?..
/* Returns the largest integer in the array */
int CompareToAll(int array[], int n)
{
int i, j;
bool isMax;/* Make sure that there is at least one element in the array.*/
if (n <= 0) return -1;
for (i = n-1; i > 0; i--)
{
isMax = true;
for (j = 0; j < n; j++) {
/* See if any value is greater.*/
if (array[j] > array[i]){
isMax = false; /* array[i] is not the largest value. */
break;
}
} /* If isMax is true, no larger valueexists; array[i] is max. */
if (isMax)
break;
}
return array[i];
}
Thank you
Yes, it’s O(n2) on average, assuming that the elements are randomly chosen. In the worst case you compare every element with every other element.
This algorithm is not optimal. It is possible to find the maximum element in an array using simple O(n) algorithm: iterate over the array once while keeping track of the largest element seen so far.