Sunday, June 25, 2006

largest element in the array by comparing to All - C#

To find out the largest element in the array by comparing to All elements method
This methd has an Big Oh notation performance of O(n2)


public static int GetIndexLargestCompareToAll(int[] numbers)
{
int currentMaxIndex = -1;
int length = numbers.Length;
bool isMax = false;

try
{
if (length == 0)
currentMaxIndex = -1;
else if (length == 1)
currentMaxIndex = 0;
else
{
for (int i = 0; i < length; i++)
{
isMax = true;
for (int j = 0; j < length; j++)
{
if (numbers[j] > numbers[i])
isMax = false;
}
if (isMax)
currentMaxIndex = i;
}
}

}
catch (Exception)
{
currentMaxIndex = -1;
}
return currentMaxIndex;
}

No comments: