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;
}

Largest Element in the Array using C #

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


public static int GetIndexLargestCompareToMax(int[] numbers)
{
int currentMaxIndex = -1;
int length = numbers.Length;

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

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