Jump to content

Binary search: Difference between revisions

m (Forgot the task tag)
Line 33:
==[[Java]]==
[[Category:Java]]
==Iterative==
...
//check will be the number we are looking for
//nums will be the array we are searching through
int hi = nums.length - 1;
int lo = 0;
int guess = (hi + lo) / 2;
while((nums[guess] != check) && (hi > lo)){
if(nums[guess] > check){
hi = guess - 1;
}else if(nums[guess] < check){
lo = guess + 1;
}
guess = (hi + lo) / 2;
}
if(hi < lo){
System.out.println(check + " not in array");
}else{
System.out.println("found " + nums[guess] + " at index " + guess);
}
...
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.