Computer Science Canada

[Tutorial] Finding the Minimum and Maximum in an Array

Author:  wtd [ Fri Oct 01, 2004 4:42 pm ]
Post subject:  [Tutorial] Finding the Minimum and Maximum in an Array

Finding Maximum

The basic algorithm

Create a variable to store your current maximum. Set this variable to the first value in your array. This will make sure that the result is a value from the array, rather than some default value that might be already larger than any value in the array.

Now, loop through the remaining values in the array. Each time, check to see if the value is greater than the current maximum. If it is, then change the current maximum to that number.

At the end of the loop, you'll have the maximum value in the array.

The code

code:
var arr : array 1 .. 4 of int := init(42, 27, 3001, 86)

var runningMax : int := arr(1)

for i : 2 .. 4
   if arr(i) > runningMax then
      runningMax := arr(i)
   end if
end for


Finding Minimum

The basic algorithm

Create a variable to store your current minimum. Set this variable to the first value in your array. This will make sure that the result is a value from the array, rather than some default value that might be already larger than any value in the array.

Now, loop through the remaining values in the array. Each time, check to see if the value is less than the current minimum. If it is, then change the current minimum to that number.

At the end of the loop, you'll have the minimum value in the array.

The code

code:
var arr : array 1 .. 4 of int := init(42, 27, 3001, 86)

var runningMin : int := arr(1)

for i : 2 .. 4
   if arr(i) < runningMin then
      runningMin := arr(i)
   end if
end for

Author:  Cervantes [ Sat Oct 02, 2004 7:01 am ]
Post subject: 

err, wtd, arr (2) needs to be replaced with arr(i)

code:

var arr : array 1 .. 4 of int := init (42, 27, 3001, 86)

var Max : int := arr (1)

for i : 2 .. 4
    if arr (i) > Max then
        Max := arr (i)
    end if
end for

code:

var arr : array 1 .. 4 of int := init(42, 27, 3001, 86)

var Min : int := arr(1)

for i : 2 .. 4
   if arr(i) < Min then
      Min := arr(i)
   end if
end for


I also changed max to Max and min to Min because max and min are built-in turing functions.

Thanks for the tutorial Smile
+BITS

Author:  wtd [ Sat Oct 02, 2004 12:23 pm ]
Post subject: 

Thanks for the eye for detail. Smile


: