线性查找,即从头到尾遍历,最坏的情况需要查找o(N)
public void test08() {
String str = "BB";
String[] strArr = new String[]{"AA", "DD", "CC", "BB", "FFF"};
boolean found = false;
for (int i = 0; i < strArr.length; i++ ) {
if (strArr[i].equals(str)) {
System.out.println("找到了");
found = true;
break;
}
}
if (!found ) {
System.out.println("没找到");
}
}
二分查找
public void test09() {
int[] arr1 = new int[]{-100, -78, -23, -5, -4, 0, 3,5, 23, 98};
int head = 0;
int end = arr1.length - 1;
int desc = 0;
boolean flag = false;
while (head <= end) {
int middle = (head + end) / 2;
System.out.println("head=" + head);
System.out.println("end=" + end);
if (arr1[middle] == desc) {
System.out.println("找到了,索引为:" + middle);
flag = true;
break;
} else if (arr1[middle] > desc) {
end = middle - 1;
} else {
head = middle + 1;
}
}
if (!flag) {
System.out.println("很遗憾,没有找到");
}
}