gunsnroses23k
BAN USER- 0of 0 votes
AnswersThere is a sorted array of integers (suppose sorted in "ascending order"). How will you find a specific element in an array? You can not use traditional iterative method to find a specific element in an array.
- gunsnroses23k in United Kingdom| Report Duplicate | Flag | PURGE
Ebay Java Developer Algorithm
Can anyone suggest me if the code below is okay? It works fine but I was wondering since someone mentioned the "mid" problem I was hoping I could use some insight. Thank you. Here's the code:
static int [] arr={1,2,3,5,6,7};
static int input=5;
int head1=0;
int tail1=arr.length-1;
int mid1=((tail1-head1)/2);
binaryRecursively(mid1);
binaryRecursively(int mid) {
if (arr[mid]==input){
System.out.println("Found Recursively - "+arr[mid] +" at index - "+mid);
}
else if (arr[mid]<input){
mid++;
binaryRecursively(mid);
}
else if (arr[mid]>input){
mid--;
binaryRecursively(mid);
}
}
Yes, Ebay asked this question for the position of Junior Java Developer. Can anyone suggest me if the code below is okay? It works fine but I was wondering since someone mentioned the "mid" problem I was hoping I could use some insight. Thank you. Here's the code:
static int [] arr={1,2,3,5,6,7};
static int input=5;
int head1=0;
int tail1=arr.length-1;
int mid1=((tail1-head1)/2);
binaryRecursively(mid1);
binaryRecursively(int mid) {
if (arr[mid]==input){
System.out.println("Found Recursively - "+arr[mid] +" at index - "+mid);
}
else if (arr[mid]<input){
mid++;
binaryRecursively(mid);
}
else if (arr[mid]>input){
mid--;
binaryRecursively(mid);
}
}
@ nitin Thanks for the input. I agree with your suggestion but if you look carefully what I did was not exactly binary search. I would rather call it a distorted form of binary search. The performance in my program can be slow but it does work as according to my code "high" & "low" are always constant & recursive method is invoked with argument of "mid" which is either just incremented or decremented (as I said this can be a lot slower than binary search for large arrays but it does work) The reason I did that was because I wanted to show them something different than what usually they would expect anyway if asked next time I would keep all that in my mind including the integer overflow case. Thanks for the help!
- gunsnroses23k May 11, 2013