• ### What is your GameDev Story?

#### Archived

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

# array handling

This topic is 5488 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Whats the fastest way to check if a number already exists in an array?

##### Share on other sites
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 on other sites
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 searcheddif = 23-2 = 21index = (x-2) * 11 / dif = 2 * 11 / 21 = 1if (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 on other sites
Thanks std::find will do the Trick

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 11
• 15
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
634149
• Total Posts
3015829
×

## Important Information

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!