Wednesday, September 22, 2010

Determining the highest element of an array of numbers

Algorithm
Given: Array of doubles
1.Declare a variable, say lowest, that will hold the highest element.
2.Initialize the variable lowest by assigning th first element of the array to it
3.Check if the next element is greater than the current value stored in highest. If the next element is greater than the current value of highest, let the value of highest be replaced by the element.
4.Repeat from step 3 until all elements are checked.
5.Give the value of highest

Method ( Implementation of the algorithm in a method)

double findHighestElement(double[] givenArray) {
double highest = givenArray[0];
for (int index=1; index < givenArray.length; index += 1) {
if (givenArray[index] > highest )
highest = givenArray[index];
}
return highest;
}

No comments:

Post a Comment