public class ArraySearch {
public static void main(String[] args) {
int[] a = {5, 9, 88, 66, 24, 23};
/* for (int i = 0; i < a.length; i++) {
if (a[i] == 88) {
System.out.println("88的元素下标为" + i);
return;
}
}
System.out.println("没有88元素");
}*/
/**
* a 被检索的数组
* elt 被检索的元素
* index 返回值
*/
int index=arraysearch(a,23);
System.out.println(index==-1 ? "该元素不存在" : "该元素的下标为" + index);
}
public static int arraysearch(int [] a, int elt){
for (int i = 0; i < a.length; i++) {
if (a[i]==elt){
return i;
}
}
return -1;
}
}
二分法查找前提是这个数组已经排好序
package com.elaixin.yzc.study;
public class search {
public static void main(String[] args) {
int [] a={100,200,666,777,888,9999};
int index=arraysearch(a,9999);
System.out.println(index==-1 ? "该元素不存在" : "该元素下标为" + index);
}
public static int arraysearch(int [] a,int elt) {
int beain = 0;
int end = a.length - 1;
while (beain <= end) {
int mid = (beain + end) / 2;
if (a[mid] == elt) {
return mid;
} else if (a[mid] < elt) {
beain = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
}