|
Bsearch() has to find an exact match on something. It can find an exact match on PART of your key, but, some part of it must match exactly.
In your example, you have this: Array(1) = 'AB' Array(2) = 'ABC' Array(3) = 'ABCD' Array(4) = 'ABCDEF' Array(5) = 'ACCDEF' Search key is ABCE123.For this example, you could search for the first 3 letters (ABC) to match. When you found a match (which could be any of elemnts 2, 3 or 4) you could then read backward and forward in the array to find the "closest" match.
However, what if you had this? Array(1) = AAAAAAA Array(2) = BBBBBBB Array(3) = CCCCCCC Array(4) = FFFFFFF Array(5) = GGGGGGG Array(6) = HHHHHHH Search key is DEFGHIJIn this case, I'd think you'd want #4 to be the "closest match" (sort of, I guess) since it's the next higher element. But you can't do that with bsearch() because there's no part of the element that matches exactly.
Instead of using bsearch(), you might be better off writing your own binary search tool. It would do this:
a) Array has 6 elements... so check element 3. b) Is key > element 3? Yes. We have elemnts 4,5,6 left, so try 5. c) Is key > element 5? No. d) IS key < element 5? YEs. We have element 4 left.e) Is key < element 4? Yes. Is key > element 3? Yes. Closest match is element 4.
Something like that...
As an Amazon Associate we earn from qualifying purchases.
This mailing list archive is Copyright 1997-2024 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].
Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.