线性和二分查找算法
public class FindTest {
public static int find(int[] arr, int data) {
for(int i = 0; i < arr.length; i++) {
if(data == arr[i]) {
return i;
}
}
return -1;
}
public static int findBinary(int[] arr, int left, int right, int data) {
if(left <= right) {
int p = (left + right)/2;
if(data == arr[p]) {
return p;
}
if(data < arr[p]) {
return findBinary(arr, left, p-1, data);
}
return findBinary(arr, p+1, right, data);
}
return -1;
}
public static void main(String[] args) {
int[] brr = {10, 20, 30, 40, 50};
int num = 25;
int res = FindTest.findBinary(brr, 0, 4, num);
if(-1 == res) {
System.out.println("元素" + num + "不存在!");
} else {
System.out.println("元素" + num + "在数组的下标为:" + res);
}
}
}