Create BinarySearch.java
parent
23dc31f9ae
commit
97eb4196e9
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.nbee.solution.practice;
|
||||||
|
|
||||||
|
class BinarySearch {
|
||||||
|
public static int binarySearchBasic(int[] nums, int target){
|
||||||
|
int i = 0 ,j = nums.length - 1;//设置指针和初始值
|
||||||
|
while (i <= j){
|
||||||
|
int mid = ((i + j) / 2);
|
||||||
|
if (target == nums[mid]){
|
||||||
|
return mid;
|
||||||
|
}
|
||||||
|
else if (target < nums[mid]){
|
||||||
|
j = mid - 1;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
j = mid + 1;
|
||||||
|
}
|
||||||
|
return mid;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue