Find the largest element in an array of numbers

Series: Common Algorithms with Ruby and JavaScript

One of the most common algorithms we usually have to deal with is:

Given an array of negative/positive integers, how to find the largest element in that array, without using max() for Ruby or Math.max() for JavaScript.

Ruby

array = [34 , 16, 1, 66, 50, 42, -91, -145]

def max(array)
  if array.length == 0
    return nil
  end
  largest = array.first
  array.each do |number|
    if largest < number
      largest = number
    end
  end
  largest
end

puts "The largest number is #{max(array1)}"
# -> The largest number is 66

 

JavaScript

var array = [34 , 16, 1, 66, 50, 42, -91, -145];

function max(array) {
  if (array.length === 0) {
    return
  }
  var largest = array[0];
  for(var i = 0; i <= array.length; i += 1) {
    if (largest < array[i]) {
      largest = array[i];
    }
  }
  return largest;
}
console.log("The largest number is " + max(array));
// -> The largest number is 66
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s