views:

139

answers:

5

Today, I went for an interview and the interviewer asked me how I would find the index of a given value (number) in a pre-sorted array like this:

$preSortedArr=array(23,32,36,41,45,54);

He also said that using recursion is not allowed.

I think the function should look like this:

function findIndexByValue($preSortedArray,$value){            
//some codes here       
}

What solution do you think he was expecting from me?

EDIT: Sorry, I forgot to add that he originally asked me to write pseudocode, but I said I didn't know. Then I tried to write it in PHP, but I think he's expecting a language-independent solution.

+2  A: 
$key = array_search("23", $array);
Chacha102
+1 because you were 11 seconds faster than me
Gordon
+2  A: 

He was likely looking for

  • array_search — Searches the array for a given value and returns the corresponding key if successful

EDIT The question is somewhat odd for the given array. There is no point in doing this with anything else than PHP's native function. An alternative would be to use while, next, key and current if you'd wanted to it by hand. This still wouldn't explain why the interviewer noted you may not use recursion.

Gordon
+5  A: 

Since he said the array was pre-sorted, he was probably expecting a binary search. A linear search (with a possible optimisation since the array is sorted - exit with failure if you find a larger value) would of course be perfectly fine on the small array in the example. Probably faster, if it matters.

Steve Jessop
I agree with Steve on this one. Normally I would say to use array_search, but he's looking for the thought process not the php function.
St. John Johnson
@John then either the interviewer or the OP used a pretty bad example for the question :)
Gordon
I guess it really depends whether this was a "do you know PHP?" question, or a "do you know algorithms?" question. If he was just looking for `array_search`, to prove you know PHP, then the fact that the array is sorted is irrelevant, and so is the ban on recursion. But actually, that's the right answer for arrays similar to the example. Maybe he was prepared for `array_search`, and had a follow-up question, "what if the array contains a million values?".
Steve Jessop
+1  A: 

He probably was not looking for any specific answer. He probably wanted to see how you think and consider different options, and explaing their pros and cons, before choosing your way of implementing the thing.

Tuomas Pelkonen
+1  A: 

The best approach is to use Binary search algorithm. Worst case complexity is o(logn)

Can binary search be implemented without recursion?
bobo
@bobo. Of course it can.
Moron
Yes. Niklaus Wirth recorded this algorithm in Standard Pascal [6] : min := 1; max := N; {array size: var A : array [1..N] of integer} repeat mid := (min + max) div 2; if x > A[mid] then min := mid + 1 else max := mid - 1; until (A[mid] = x) or (min > max);