calc median

This commit is contained in:
olli 2024-08-16 17:27:41 +02:00
parent 4292b8e4dc
commit d61329011b

27
gaboshlib/g_median.sh Normal file
View File

@ -0,0 +1,27 @@
function g_median {
unset g_median_result
# Array with numbers
local g_numbers=("$@")
# sort array
local g_sorted_numbers=($(printf "%s\n" "${g_numbers[@]}" | sort -n))
# number of elements
local g_num_elements=${#g_sorted_numbers[@]}
# calculate the middle
local g_middle=$((num_elements/2))
local g_median
# Falls die Anzahl der Elemente ungerade ist
if ((g_num_elements % 2 == 1)); then
g_median=${sorted_numbers[middle]}
else
# Falls die Anzahl der Elemente gerade ist
g_calc "(${sorted_numbers[middle - 1]} + ${sorted_numbers[middle]}) / 2"
g_median=$g_calc_result
fi
g_median_result=$g_median
}