@Rafi: Try this:
int arrExsits( int* arr, int size, int elem)
{
int temp = arr[0];
arr[0] = elem;
while( arr[--size] != elem );
arr[0] = temp;
return a[size] == elem ? size : -1;
}
n+1 comparisons, and it leaves the array unaltered.
Dave
On Sunday, September 30, 2012 4:27:27 AM UTC-5, rafi wrote:
Hi
i was in an interview and was given a simple function
int arrExsits(int* arr,int size,int elem){
for (int i=0;isize;++i)
if(elem==arr[i])
return i;
return -1;
}
this function does 2n compares
n- the if statment
n-check that i is smaller then size
i was suppose to give an optimal (less compares) solution so i gave
int arrExsits(int* arr,int size,int elem){
if (arr[size-1]==elem)
return size-1;
arr[size-1]=elem]
for (int i=0;;++i)
if(elem==arr[i]){
if (i!=size-1)
return i;
return -1;
}
this solution works and it has n+2 compares the first one another n and
the second inner if.
they told me it's good (and I've passed) but they told just for my
knowledge that there is a better N compare solution.
I've searched the web but couldn't find it.
anybody knows?
Thanks
--
You received this message because you are subscribed to the Google Groups
Algorithm Geeks group.
To view this discussion on the web visit
https://groups.google.com/d/msg/algogeeks/-/xf30WpSdP_oJ.
To post to this group, send email to algogeeks@googlegroups.com.
To unsubscribe from this group, send email to
algogeeks+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.