Among the many pieces of obvious functionality missing from Crystal is a median function that will operate on an array. The median is not horribly difficult to calculate, but in order to do so you need a sorted list of values. Another obvious thing Crystal is missing is an array sort function. The median of a list is its middle value by position such that of the set (1, 3, 3, 4, 6) the median is 3 while the average is 3.4. While it does not look very useful with a short set of only five elements, it is often useful when you have one or two hundred of them. It is often much more useful than an average when you have a lot of redundancy in your set.
The simplest sort worth implementing is the Cocktail Sort, also known as the bidirectional bubble sort, cocktail shaker sort, shaker sort, ripple sort, shuttle sort or happy hour sort. The name comes from the fact that it iterates from one end of the list to the other, and then back again. It deals better with lists which are already in order (or close to it) than the bubble sort (the simplest sort algorithm) due to this characteristic. Cocktail sorts get faster when the list is more ordered, while bubble sorts go slower.
Shared NumberVar Array NumberList;
local numbervar loop1 := 0;
local numbervar loop2 := 0;
local numbervar temp := 0;
//
for loop2:=1 to ubound(NumberList)-1 do(
for loop1:=1 to ubound(NumberList)-loop2 do(
if NumberList[loop1] > NumberList[loop1+1] then
(temp := NumberList[loop1];
NumberList[loop1] := NumberList[loop1+1];
NumberList[loop1+1] := temp)));
NumberList is the array to be sorted. In this case it's an array of NumberVar values but it could be any type because Crystal does have type-sensitive comparison operators. loop1 and loop2 are offset counter variables. Temp is used to hold the value being moved from one position to another.