Tuesday, September 21, 2010

Determining the lowest element of an array

Algorithm

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

Method ( Implementation of the algorithm in a method)

int findLowestElement(int[] givenArray) {
int lowest = givenArray[0];
for (int index=1; index < givenArray.length; index += 1) {
if (givenArray[index] < lowest )
lowest = givenArray[index];
}
return lowest;
}

No comments:

Post a Comment