二分法查找:
例如: 1 , 9 , 5 , 6 , 7 , 2 , 4
start=0; end=6;
mid=(start+end)/2;
如果findValue等于arr[mid],则直接return mid;
如果findValue小于arr[mid],则令end=mid-1;
1 , 9 , 5 , 6 , 7 , 2 , 4
start=0; end=2;
如果findValue大于arr[mid],则令start=mid+1;
1 , 9 , 5 , 6 , 7 , 2 , 4
start=4; end=6;
package stuClass;
import java.util.Arrays;
public class Test02 {
public static void main(String[] args) {
int[] arr= {1,9,5,6,7,2,4};
Test02 tt=new Test02();
int x=tt.getSort(arr, 0, arr.length-1, 1);
System.out.println(x);
System.out.println(Arrays.toString(arr));
}
public int getSort(int[] arr,int start,int end,int findValue) {
Arrays.sort(arr);
if(arr==null) {
return -1;
}
while(start<=end) {
int mid=(start+end)/2;
int midValue=arr[mid];
if(findValue<midValue) {
end=mid-1;
}else if(midValue==findValue) {
return mid;
}else {
start=mid+1;
}
}
return -1;
}
}
与君共勉之~