Saturday, December 18, 2010

Find the greatest element in an unordered array of elements


To find the element with max value in an unordered array or any collection of elements, the simplest strategy is brute force. Here is the algorithm in pseudocode (I use an array for easy understanding):


//initialize maxValue to first element
maxValue = array[0];
//loop through the array and compare each element with the max value
for i = 1 to array.size - 1 do   
  if array[i] > maxValue  
  //if an element is greater than the current maxValue  
  //we make the maxValue the same with the current element
      maxValue = array[i];
return maxValue;


The strategy is to use a variable called maxValue to hold the greatest value we find. First initialize the maxValue to the first element. And as we go through the array, we change maxValue to whichever element that has higher value than maxValue. Keep doing that until we reach the end. By that time, maxValue holds the greatest value in the array.


Notice: The algorithm's time efficiency is O(n). This means that to find the max element in an array of 1,000 elements, the algorithm must do 1,000 comparisons :)


Got question / suggestion? Please post in the comment section below and I'll answer them as best as I can. Peace!

No comments:

Post a Comment