Finding middle numbers in pseudocode

  • Thread starter Thread starter Travian
  • Start date Start date
  • Tags Tags
    Numbers
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 8K views
Travian
Messages
64
Reaction score
0

Homework Statement


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.


Homework Equations





The Attempt at a Solution



Code:
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 can't imagine how to do it? i think there should be some arrays involved. any ideas?
 
Physics news on Phys.org
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).
 
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:
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.