Binary search: Difference between revisions
Content added Content deleted
m (Forgot the task tag) |
|||
Line 33: | Line 33: | ||
==[[Java]]== |
==[[Java]]== |
||
[[Category: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); |
|||
} |
|||
... |