Created
December 16, 2013 22:17
-
-
Save prat0318/7995456 to your computer and use it in GitHub Desktop.
binary search without outer bound.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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