home *** CD-ROM | disk | FTP | other *** search
- From: akcs.joehorn@hpcvbbs.cv.hp.com (Joseph K. Horn)
- Date: Sat, 12 Dec 1992 11:40:02 GMT
- Subject: Insert into Sorted List
- Message-ID: <2b29cf68.2387comp.sys.hp48@hpcvbbs.cv.hp.com>
- Path: sparky!uunet!haven.umd.edu!darwin.sura.net!europa.asd.contel.com!emory!swrinde!zaphod.mps.ohio-state.edu!sdd.hp.com!hp-cv!hp-pcd!hpcvra!rnews!hpcvbbs!akcs.joehorn
- Newsgroups: comp.sys.hp48
- Lines: 32
-
- I challenged my students to write a program (in User RPL) that inserts
- a real number into a list of pre-sorted reals, in such a way that the
- list is still in order. They all developed linear-search methods
- which work okay, but are slow. The following "binary search" method
- is much faster. Their fastest program took over 38 seconds to insert
- 888.8 into a list of the integers 1 through 1000; the program below
- takes less than two seconds.
-
- Is there a better way?
-
- %%HP: T(3)A(D)F(.);
- @ ORD3 by Joe Horn; inserts a real into a list in the right place.
- @ 2: List of pre-sorted reals; 1: real
- \<<
- SWAP OBJ\-> DUP 2 + ROLL OVER 6 + 5
- WHILE DUP2 - 1 >
- REPEAT DUP2 + 2 / CEIL DUP PICK 5 PICK
- IF >
- THEN SWAP DROP
- ELSE ROT DROP SWAP
- END
- END DROP 4 -
- ROLLD 1 + \->LIST
- \>>
-
- Example: { 5 7 9 11 13 } 10 ORD3 --> { 5 7 9 10 11 13 }
-
- Note: Program must be able to handle the possibility of insertion at
- the ends of the list. The program above also just happens to be able
- to handle the case of insertion into an empty list.
-
- -Joe Horn-
-
-