#!/bin/bash # This program computes the median of a list of integers on the command line. # If there are no arguments, then it asks the user to enter them on # separate lines. Then it prints the median (middle # value after sorting). If there are an even number of numbers, then # the median is the average of the 2 middle values, rounding down # Copy the command line into array n i=0 # current element of n finished=0 # 1 (true) when there is no more interactive input expected while (($# > 0)); do ((n[i] = $1)) shift ((i++)) finished=1 done # Else if there are no arguments then ask the user to enter some numbers if ((!finished)); then echo Enter some numbers, one per line. Enter a blank line when done. while ((!finished)); do read x if [ "$x" == "" ]; then finished=1 else ((n[i++]=x)) fi done fi # If n is empty then give up size=${#n[*]} if ((size==0)); then echo Error: at least one number is expected exit 1 fi # Bubble sort n ((i=size-1)) while ((i>0)); do j=0 while ((jn[j+1])); then #swap so n[j] <= n[j+1] ((t=n[j])) ((n[j]=n[j+1])) ((n[j+1]=t)) fi ((++j)) done ((--i)) done # Compute the median from the middle 1 or 2 elements ((mid = size/2)) if ((size % 2 == 0)); then ((median = (n[mid] + n[mid-1]) / 2)) else ((median = n[mid])) fi # Print the sorted array and the median echo The median of ${n[*]} is $median