new tasks
This commit is contained in:
parent
2a4d27cea0
commit
80737d5a6a
1194 changed files with 15353 additions and 1 deletions
21
Task/Binary_search/Java/binary_search-2.java
Normal file
21
Task/Binary_search/Java/binary_search-2.java
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
public static void main(String[] args){
|
||||
int[] searchMe;
|
||||
int someNumber;
|
||||
...
|
||||
int index = binarySearch(searchMe, someNumber, 0, searchMe.length);
|
||||
System.out.println(someNumber + ((index == -1) ? " is not in the array" : (" is at index " + index)));
|
||||
...
|
||||
}
|
||||
|
||||
public static int binarySearch(int[] nums, int check, int lo, int hi){
|
||||
if(hi < lo){
|
||||
return -1; //impossible index for "not found"
|
||||
}
|
||||
int guess = (hi + lo) / 2;
|
||||
if(nums[guess] > check){
|
||||
return binarySearch(nums, check, lo, guess - 1);
|
||||
}else if(nums[guess]<check){
|
||||
return binarySearch(nums, check, guess + 1, hi);
|
||||
}
|
||||
return guess;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue