home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!gatech!usenet.ins.cwru.edu!agate!mickey!bsmith
- From: bsmith@mickey.NoSubdomain.NoDomain (Brian Smith)
- Newsgroups: comp.programming
- Subject: Re: is it possible to find max & next smallest in one pass?
- Date: 24 Jan 1993 05:24:27 GMT
- Organization: University of California, Berkeley
- Lines: 37
- Sender: bsmith@mickey (Brian Smith)
- Distribution: world
- Message-ID: <1jt96b$kc9@agate.berkeley.edu>
- References: <1993Jan24.040702.6193@emr1.emr.ca>
- NNTP-Posting-Host: mickey.cs.berkeley.edu
-
- In article <1993Jan24.040702.6193@emr1.emr.ca>, 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?
- |>
-
-
- how about this:
-
- /* Keep max2 >= max1 */
- max1 = max2 = x[0];
- for (i=1; i<N; i++) {
- if (x[i] > max1) {
- if (x[i] > max2) {
- max1 = max2;
- max2 = x[i];
- } else {
- max1 = x[i];
- }
- }
- }
- /* At this point, max2 is largest, min1 is next largest */
-
- This does 2*N comparisons in the worst case, but (1+epsilon)*N comparisons
- in the average case.
-
- In an actual implementation, it'd be worth it to unroll the loop a few times
- to make it run faster, unless your comparison operator is very slow.
-
- -------
- Brian C. Smith arpa: bsmith@cs.Berkeley.EDU
- University of California, Berkeley uucp: uunet!ucbvax!postgres!bsmith
- Computer Sciences Department phone: (510)642-9585
-