home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!sun4nl!and!jos
- From: jos@and.nl (Jos Horsmeier)
- Newsgroups: comp.programming
- Subject: Re: is it possible to find max & next smallest in one pass?
- Message-ID: <4400@dozo.and.nl>
- Date: 24 Jan 93 12:49:32 GMT
- References: <1993Jan24.040702.6193@emr1.emr.ca> <asean.727858796@armstrong.ecn.purdue.edu>
- Organization: AND Software BV Rotterdam
- Lines: 45
-
- In article <asean.727858796@armstrong.ecn.purdue.edu> asean@armstrong.ecn.purdue.edu (Sean Ahern) writes:
- |jagrant@emr1.emr.ca (John Grant) writes:
- |>Given an array of values, is it possible to find the maximum of
- |>the array and the next smallest value in a single pass? The reason
- |>I want it in one pass, is that the array is actually a data file
- |>of a million float values.
- |>
- |>If so, I guess the same single pass could also find the min and next
- |>highest value too?
- |
- |If you were able to do this, the algorithm should be able to extend to the
- |next smallest, and the next, with little or no trouble.
- |
- |But the requirement of the algorithm was to do this in one pass. This would
- |give us an O(n) sorting algorithm that works on arbitrary data. I don't
- |believe such an animal exists with only one processor.
-
- I beg to differ here. Lets do some big Oh calculations. Given n elements
- in an array, one can find the maximum value in O(n) operations. One can
- find the next value in O(n) operations too, so both can be done in
- O(n)+O(n)= O(2*n) operations. But constants don't count here, so the
- whole job can be done uisng O(n) operations. Finding three elements,
- takes O(3*n)= O(n) operations, and so on. But sorting all n elements
- this way takes up O(n*n) operations, which is, in fact, quite a lousy
- way of sorting an array. But lets get back to the original problem,
- here is a simple solution:
-
- m1 = a[1] // m1 >= m2
- m2 = a[1]
-
- loop: i = 2 .. n // compare a[i], m1 and m2
-
- if a[i] > m2 then // is it a candidate?
- m2 = a[i]
-
- if m2 > m1 then // is it the largest?
- swap m1, m2
-
- result: m1, m2
-
- I hope this clarifies things a bit,
-
- kind regards,
-
- Jos aka jos@and.nl
-