#!/bin/csh # This program computes the median of a list of integers on the command line. # If there are no arguments, then it sks the user to enter them on # one line separated by spaces. 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 # Get a list of numbers from the command line or user, store in $n set n = ( $* ) if ($#n == 0) then echo -n "Enter some numbers: " set n=( `echo $<` ) endif if ($#n < 1) then echo "Error: no numbers" exit 1 endif # bubble sort $n @ i = $#n while ( $i > 0 ) @ j = $#n while ( $j > 1 ) @ j1 = $j - 1 if ($n[$j1] > $n[$j]) then @ t = $n[$j] # swap @ n[$j] = $n[$j1] @ n[$j1] = $t endif @ j = $j1 end @ i-- end # compute the median @ mid = $#n / 2 @ mid1 = $mid + 1 if ($#n % 2 == 0) then @ median = ($n[$mid] + $n[$mid1]) / 2; else @ median = $n[$mid1] endif echo The median of $n is $median