Skip to content

Instantly share code, notes, and snippets.

@prat0318
Created December 16, 2013 22:17
Show Gist options
  • Save prat0318/7995456 to your computer and use it in GitHub Desktop.
Save prat0318/7995456 to your computer and use it in GitHub Desktop.
binary search without outer bound.
class MyArray {
// returns null, if out-of-bounds index, returns value otherwise
public Integer get(Integer index);
public Integer search(Integer value) {
// if(get(0) == value)return 0;
int base = 0;
while(true) {
int index_jump = 1;
while(get(base+index_jump) != null && get(base+index_jump) <= value) {
if(get(base+index_jump) == value) return base+index_jump;
index_jump *= 2;
}
//Start again from index_jump as 1, increase the base, in infinite loop
if(get(base + index_jump) == null) {base += index_jump/2; continue;}
// If found an upper bound, return with binary search
return binary_search(value, base+index_jump/2, base+index_jump);
}
}
public Integer binary_search(num, start, end) {
if(end < start) return -1;
int mid = start + end;
if(get(mid) == num) return mid;
if(get(mid) < num)
return binary_search(num, mid+1, end);
else
return binary_search(num, start, mid+1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment