# Finding middle numbers in pseudocode

1. Aug 26, 2010

### Travian

1. The problem statement, all variables and given/known data
Write an algorithm in pseudocode that allows the user to input the selling prices of all homes at Kingston sold during 2009 and determine the median selling price. The median of a list of N numbers is as follows:

the middle number of the sorted list, if N is odd
the average of the two middle numbers in the sorted list if N is even.

The user will terminate the input by entering a zero or a negative number.

2. Relevant equations

3. The attempt at a solution

Code (Text):

Declare Counter as integer
Declare Number as float
Set Counter = 0
Set Number = -1
Display "Enter a number. Enter a zero or negative number to finish"
WHILE Number > 0
?????
ENDWHILE

i cant imagine how to do it? i think there should be some arrays involved. any ideas?

2. Aug 26, 2010

### Staff: Mentor

In comparison to the other problems you posted recently, this one is a lot more difficult. One approach would be to use an array that is more than large enough, then cycle through the sales prices, storing them in the array. After the numbers are in the array sort the sales prices (the non-zero values in the array), count them, and then pick the middle number (odd number of prices) or the average of the two numbers in the middle (even number of prices).

3. Aug 27, 2010

### minger

I think that there are various sorting algorithms, however, you don't need to sort your entire array. By that, I mean you're only interested in whatever number lies right in the middle. So, if you have N number of prices, then you can do something like:
Code (Text):

REAL,DIMENSION(:),ALLOCATABLE :: data,sorted

!--Input your data here

DO i=1,N/2
!--Find the smallest entry
temp = 1.e99
DO j=1,N
IF ( data(j) .LT. temp ) THEN
temp = data(j)
END IF
END DO
sorted(i) = temp
END DO

!--We now have the first half of data sorted.

You then need to find a clever way to do your DO loop such that you always loop the correct number of times such that you have enough (and just enough for computational efficiency) data to find the median.

Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook