KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Finding the median value in an array
PRODUCT: 4D | VERSION: | PLATFORM: Mac & Win
Published On: February 11, 2000

Assuming that you have a series of numeric values, here is the easiest way of getting the middle value. If you sort the array, the middle value will appear in the middle elements in the array. This middle value is also referred to as the median value.

Cut and Paste the following code example into your own 4D project

 ` example array
ARRAY LONGINT(Numbers;6)
Numbers{1}:=99
Numbers{2}:=2
Numbers{3}:=10
Numbers{4}:=300
Numbers{5}:=45
Numbers{6}:=250

 ` the code needed to get median value
C_LONGINT($middle)

SORT ARRAY(Numbers) ` sort array to make it easy to get middle value

$middle:=Int(Size of array(Numbers)/2)
If ((Size of array(Numbers)/2)=$middle) ` if there are even number of elements
 $median_value:=((Numbers{$middle}+Numbers{$middle+1})\2) ` average the 2 middle values
Else ` if there are odd number of elements
 $median_value:=Numbers{$middle+1} ` get the middle value
End if