This topic is now archived and is closed to further replies.


array handling

Recommended Posts

Fruny    1658
If the array is sorted:
T array[size];
bool found = std::binary_search( array, array+size, value );

If not:
T array[size];
bool found = std::find(array, array+size, value) != array+size;

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”
— Brian W. Kernighan (C programming language co-inventor)

[edited by - Fruny on January 15, 2004 2:37:29 AM]

Share this post

Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
If the numbers are sorted and pretty evenly in the array, like

2 4 7 9 9 12 15 16 16 20 23

then interpolation search is faster than binary search. It''s kind of like binary search but instead of just selecting the middle element, it selects a value that is interpolated between start and end points, knowing the value to be searched. It''s the same as if you look up a number from a phone book. When you''re looking for ''Bubba'' (that being the last name) you won''t start from the middle (as you''d do with binary search), you start searching from somewhere near the beginning of the book.

In the above list there are 11 numbers. If you''re looking for 4, then you should do the initial step like this:

x = 4 ## value to be searched

dif = 23-2 = 21
index = (x-2) * 11 / dif = 2 * 11 / 21 = 1
if (array[index] == 4) return success
..fix bounds and repeat the above appropriately

Yay it found 4 from the array at first guess, at position 1. But as you might know, the division needed at each step takes some time too. So this gives benefit only for very large arrays.

STL doesn''t have an implementation for this, though.

Share this post

Link to post
Share on other sites