1.[代码]二分法查找
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package consolet;
/**
*
* @author Brin
*/
public class ConsoleT {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println(find(arr, 2));
}
public static int find(int[] arr, int target) {
int mid = arr.length / 2;
int start = 0;
int end = arr.length - 1;
while (start < mid && mid < end) {
if (arr[mid] > target) {
end = mid;
} else if (arr[mid] < target) {
start = mid;
} else {
return mid;
}
mid = (start + end) / 2;
}
return -1;
}
}