recursive search function
i have written a simple recursive search function to search an array for a given number.
Code:
int SearchArray( int iNum[], int iStart, int iEnd, int iSearchNum )
{
//break out clauses
if ( iNum[ iStart ] == iSearchNum )
{
return iStart;
}
else if ( iNum[ iEnd ] == iSearchNum )
{
return iEnd;
}
//else if ( sizeof( iNum ) / sizeof( int ) <= 2 ) THIS DOESNT WORK!!
else if ( iEnd -iStart <= 1 )
{
//number not in array so inform user and return 0
printf("number not found!!\n");
return 0;
}
//find the middle of the current array
int iMid = ( iEnd - iStart ) / 2 + iStart; //if first itteration i start will be 0 so same as iend / 2 ie middle of the whole array
//make sure imid isnt equal to searchnum
if ( iNum[ iMid ] == iSearchNum )
{
return iMid;
}
//if imid is less than isearchnum send second half of the current array back round
else if ( iNum[ iMid ] < iSearchNum )
{
return SearchArray( iNum, iMid, iEnd, iSearchNum );
}
//imid is greater than isearchnum so send first half of the current array back round
else
{
return SearchArray( iNum, iStart, iMid, iSearchNum );
}
}
as you can see from the comment on line 12 my first attempt caused warning: ‘sizeof’ on array function parameter ‘iNum’ will return size of ‘int *’ [-Wsizeof-array-argument]| is there a better way round this.
Also would it be better to pass the index via a pointer rather than return it as an int