Created
February 1, 2012 12:00
-
-
Save eZanmoto/1716744 to your computer and use it in GitHub Desktop.
find
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int find ( int target, const int *array, const size_t size ) { | |
int index = 0; | |
while ( index < size && array[ index ] != target ) | |
index++; | |
return index < size ? index : -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The last line isn't very readable, but this can be abstracted into an intention-revealing function, say, get_in_range( i, min, max ), which returns i if the variable is in range, and -1 otherwise. The benefit of the one-liner is that it takes constant time. Is it really better though?
A pretend disassembly of
return ( index % size ) + ( index / size * -1 );
So this weighs in at 12 instructions (I'm not going to compute sizes). So a more descriptive version of the last line would be
which I'll pretend to disassemble again
So this weighs in at only 9 instructions, and is much more clear, so I'm going to change this gist :)