/****************************************************** Our High School (OHS) needs a program that can sort tests grades in order from smallest to largest. Then the program should calculate the mean and median. This program performs those tasks, inputting numbers, sorting the entire list, and then printing the results. *******************************************************/ int[] nums = new int[1000]; // list of numbers int count = 0; // number of entries in the list void setup() { int score = 0; while(score >= 0) { score = int(input("Type a test score:") ); if(score >= 0) { nums[count] = score; count = count + 1; sort(); printNums(); println( "Mean = " + mean() ); println( "Median = " + median() ); } } } void sort() // pre-condition : nums contains as many items as COUNT says // post-condition: nums is sorted, smallest to largest // algorithm : performs a simple BubbleSort { for(int pass = 0; pass < count; pass = pass+1) { for(int x = 0; x < count - 1; x = x + 1) { if( nums[x] > nums[x+1] ) { int temp = nums[x]; nums[x] = nums[x+1]; nums[x+1] = temp; } } } } void printNums() { for(int x = 0; x < count; x = x+1) { println( nums[x] ); } println("=========="); } float mean() { float total = 0; for(int x=0; x < count ; x = x+1) { total = total + nums[x]; } return total / count; } float median() { if(count % 2 == 1) // odd number of items, so one is exactly in the middle { int middle = count / 2; return nums[middle]; } else // even number of items, so average the 2 middle nums { int m1 = count / 2; int m2 = m1 - 1; return (nums[m1]+nums[m2]) / 2.0; } } public String input(String prompt) { return javax.swing.JOptionPane.showInputDialog(null,prompt); } public void output(String message) { javax.swing.JOptionPane.showMessageDialog(null,message); } |
Two very common data-processing tasks are sorting and
searching. To write a clear and understandable program,
we use a separate method
for each of these tasks. The program contains further
methods for calculate the
mean (average) and the median values for the data in
the array. The sort( ) method
is a standard Bubble Sort
algorithm.
The median calculation
only functions if the data has already been sorted - then the
number in the middle
of the list is the median. The middle position is calculated
by dividing count / 2. But if there are an even number
of data items, say 10, then there is no item in the middle of the
list. In that case, it calculates the average
of the two items nearest the middle. The command if(count % 2 == 1) checks
whether there is an odd number
of data items.
The method for calculating the mean works without sorting the
data.