Find array index if given value
For example you can define the corresponding function the following way
size_t FindIndex( const int a[], size_t size, int value )
{
size_t index = 0;
while ( index < size && a[index] != value ) ++index;
return ( index == size ? -1 : index );
}
Also instead of type size_t you can use type int.
But the better way is to use standard algorithm std::find
or std::find_if
declared in header <algorithm>
provided that you use C++
For example
#include <algorithm>
#include <iterator>
int main()
{
int a[] = { 4, 7, 8 };
auto it = std::find( std::begin( a ), std::end( a ), 7 );
if ( it != std::end( a ) )
{
std::cout << "The index of the element with value 7 is "
<< std::distance( std::begin( a ), it )
<< std::endl;
}
}
The output is
The index of the element with value 7 is 1
Otherwise you have to write the function yourself as I showed abve.:)
If the array is sorted you can use standard C function bsearch
declared in header <stdlib.h>
For example
#include <stdio.h>
#include <stdlib.h>
int cmp( const void *lhs, const void *rhs )
{
if ( *( const int * )lhs < *( const int * )rhs ) return -1;
else if ( *( const int * )rhs < *( const int * )lhs ) return 1;
else return 0;
}
int main()
{
int a[] = { 4, 7, 8 };
int x = 7;
int *p = ( int * )bsearch( &x, a, 3, sizeof( int ), cmp );
if ( p != NULL ) printf( "%d\n", p - a );
return 0;
}
First its important that the argument list contain size information for the array, i.e. passing a pointer to an array only does not provide enough information to know how many elements the array has. The argument decays into a pointer type with no size information to the function.
So given that, you could do something like this:
int findIndex(int *array, size_t size, int target)
{
int i=0;
while((i<size) && (array[i] != target)) i++;
return (i<size) ? (i) : (-1);
}
For small arrays this approach will be fine. For very large arrays, some sorting and a binary search would improve performance