home *** CD-ROM | disk | FTP | other *** search
- #ifndef __RWTBSEARCH_H__
- #define __RWTBSEARCH_H__
- pragma push_align_members(64);
-
- /*
- * Parameterized binary search; this version allows duplicate keys
- *
- * $Header: E:/vcs/rw/tbsearch.h_v 1.1 04 Mar 1992 10:16:40 KEFFER $
- *
- ****************************************************************************
- *
- * Rogue Wave Software, Inc.
- * P.O. Box 2328
- * Corvallis, OR 97339
- *
- * Copyright (C) 1992. This software is subject to copyright
- * protection under the laws of the United States and other countries.
- *
- ***************************************************************************
- *
- * This binary search routine differs from the ANSI C version.
- * 1) If duplicate items exist, it returns the index of the first instance.
- * 2) If an item is not in the table, it returns the index where it
- * should be inserted. Hence, it is useful for insertion sorts.
- *
- ***************************************************************************
- *
- * $Log: E:/vcs/rw/tbsearch.h_v $
- *
- * Rev 1.1 04 Mar 1992 10:16:40 KEFFER
- *
- *
- * Rev 1.0 02 Mar 1992 16:10:50 KEFFER
- * Initial revision.
- */
-
- #ifndef __RWDEFS_H__
- # include "rw/defs.h"
- #endif
-
- STARTWRAP
- #include <stdlib.h>
- ENDWRAP
-
- template <class T> int
- RWTbsearch(T key, const T* base, unsigned nelem)
- {
- if (nelem==0) return 0;
- int top = nelem - 1;
- int bottom = 0;
- int middle;
-
- while (top>bottom) {
- middle = (top+bottom) >> 1;
- if ( *(base+middle) < key)
- bottom = middle + 1;
- else
- top = middle;
- }
-
- if ( *(base+top) == key ){
- // Found it. Now search downwards for the first instance.
- while ( top && *(base+top-1) == key ) --top;
- }
- else {
- // Not found; Search for where it should be inserted.
- while (top < nelem && *(base+top)< key) ++top;
- }
- return top;
- }
-
- template <class T> inline int
- RWTbsearch(T key, const T* base, const unsigned nelem){
- RWTbsearch(key, base, (unsigned)nelem);
- }
-
- pragma pop_align_members();
- #endif /* __RWTBSEARCH_H__ */
-