Largest Element in a List

excerpt: This covers the basic building blocks Linear Scan and Value Comparison. tags: linear-scan value-comparison pairwise-comparison

Write a function that returns the largest element in a list. The array is not sorted.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def largest(a)
  result = a[0]
  
  for i in (1..a.size-1)
    if a[i] > result
      result = a[i]
    end
  end
  
  result
end

p largest([10,4,3,5,2,9,14,3])

Building Blocks

  • Linear Scan
  • Value Comparison
  • Pairwise Comparison