home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / programm / 3569 < prev    next >
Encoding:
Text File  |  1993-01-24  |  2.0 KB  |  61 lines

  1. Path: sparky!uunet!paladin.american.edu!darwin.sura.net!seismo!black
  2. From: black@seismo.CSS.GOV (Mike Black)
  3. Newsgroups: comp.programming
  4. Subject: Re: is it possible to find max & next smallest in one pass?
  5. Message-ID: <51915@seismo.CSS.GOV>
  6. Date: 24 Jan 93 14:49:57 GMT
  7. References: <1993Jan24.040702.6193@emr1.emr.ca>
  8. Sender: usenet@seismo.CSS.GOV
  9. Organization: Center for Seismic Studies, Arlington, VA
  10. Lines: 48
  11. Nntp-Posting-Host: beno.css.gov
  12.  
  13. In article <1993Jan24.040702.6193@emr1.emr.ca> jagrant@emr1.emr.ca (John Grant) writes:
  14. >Given an array of values, is it possible to find the maximum of
  15. >the array and the next smallest value in a single pass?  The reason
  16. >I want it in one pass, is that the array is actually a data file
  17. >of a million float values.
  18. >
  19. >If so, I guess the same single pass could also find the min and next
  20. >highest value too?
  21. >
  22.  
  23. Seems to me that life is simpler than everyone makes it :-)
  24.  
  25. Why compare BOTH numbers??  If we find a new max, then the old max is
  26. obviously the next highest, isn't it?? The same would follow for however
  27. many maxes you wish to find.  No more than one comparison necessary.
  28.  
  29.  
  30. /* Finds the maximum and next-maximum of of first 1000 pseudo-random numbers. 
  31.  * We'll divide by 1000.0 just to get a floating point number. 
  32.  * Add a similar primer and one more if-check and you can find the min 
  33.  *   and next-min too. 
  34.  */
  35.  
  36. main()
  37. {
  38.     float value, max1, max2, tmp;
  39.     int i;
  40.     max1 = random() / 1000.0; /* Prime the pump */
  41.     max2 = random() / 1000.0;
  42.     if (max1 > max2) { /* Swap the first two if necessary */
  43.         tmp = max1;
  44.         max1 = max2;
  45.         max2 = tmp;
  46.     }
  47.     for (i = 2; i < 1000; i++) {
  48.         value = random() / 1000.0;
  49.         ivalue(value > max1) { /* New max and demote old one */
  50.             max2 = max1;
  51.             max1 = value;
  52.         }
  53.     }
  54.     printf("%g %g\n", max1, max2);
  55. }
  56. -- 
  57. -----------------------------------------------------------------------------
  58.  black@beno.CSS.GOV             land line: 407-676-2923  | I want a computer
  59.  real home: Melbourne, FL       home line: 407-242-8619  | that does it all!
  60.  CSI Inc, Computer Software Innovations, Palm Bay, FL
  61.