home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / programm / 3574 < prev    next >
Encoding:
Internet Message Format  |  1993-01-24  |  1.6 KB

  1. Path: sparky!uunet!europa.asd.contel.com!howland.reston.ans.net!spool.mu.edu!hri.com!noc.near.net!ceylon!news.tufts.edu!news.tufts.edu!gowen
  2. From: gowen@jade.tufts.edu (G. Lee Owen)
  3. Newsgroups: comp.programming
  4. Subject: Re: is it possible to find max & next smallest in one pass?
  5. Message-ID: <GOWEN.93Jan24160711@jade.tufts.edu>
  6. Date: 24 Jan 93 21:19:09 GMT
  7. References: <1993Jan24.040702.6193@emr1.emr.ca>
  8. Sender: news@news.tufts.edu (USENET News System)
  9. Distribution: na
  10. Organization: Tufts University - Medford, MA
  11. Lines: 29
  12. In-Reply-To: jagrant@emr1.emr.ca's message of 24 Jan 93 04:07:02 GMT
  13.  
  14.  
  15. > Given an array of values, is it possible to find the maximum of
  16. > the array and the next smallest value in a single pass?  The reason
  17.     Yes.  Simple solution would be
  18.  
  19. float max = array[0]; 
  20. float min = array[0];
  21. for (i=0; i<ARRAYMAX; i++) {
  22.   if (array[i] < min) min = array[i];
  23.   if (array[i] > max) max = array[i];    
  24. }
  25.  
  26.     Example is in C, should be easily translatable to most
  27. languages. 
  28.  
  29. > If so, I guess the same single pass could also find the min and next
  30. > highest value too?
  31.     Of course, but not quite as simply.  You keep a second
  32. variable -- say, max2 and min2 -- and when you find a new min, min2
  33. gets the contents of min before min gets the contents of array[i].
  34. You also have to allow for the case of equal numbers, and you need 
  35. to find a way to set it to the 2nd min if there is nothing less than
  36. array[0] (that is, the case where the contents of min are never
  37. changed).  (of course, max as well).
  38.  
  39. --
  40. --Greg Owen
  41.     gowen@forte.cs.tufts.edu, gowen@jade.tufts.edu
  42. "C Spot. C Spot run. C Spot run without a core dump! Run, Spot, Run!"
  43.