Index Match
Collapse Content
Show Content
Given a sorted Array ar
of integers with no duplicates, find the spot where ar[i] == i
.
It's super-easy to find a solution in O(n)
time, but can you code an O(log n)
solution?
Challenge
Print the index where they match, or -1 if there is none.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
曾國峻
Feb 14, 10:04 PMI have implemented binary search by recursion.
Here is my code:
static void doStuff(int[] ar){
//your code here
int low = 0;
int high = ar.length-1;
}
static int find(int low,int high,int[] ar,int i){
int mid = (low+high)/2;
}
I can't figure out what wrong with it.
Could anyone can give me some advices?
Paul
May 10, 9:13 AM曾國峻 I needed to keep track of the index and pass it back up the recursion to solve it. Because each time the binary search needed to look at the > side of the array, the index forgets about the lower half of the array. Here is my solution in Ruby:
def index_match(ar, index=0)
end
mike
Sep 4, 3:05 PMBetter to solve without recursion. maybe can be a bit more elegant, but works.