- 线性查找
public class Array{
public static void main(String[] args){
int[] array1=new int[]{1,2,3,4,5,6,7,8,9};
int cha=5;
//防止两句话同时出现
boolean isFlag=ture;
for(int i=0;i<arr.length;i++){
if(cha.equals(array1[i])){
System.out.prinln("成功找到该元素,位置为"+i);
isFlag=false;
break;
}
}if(isFlag){
System.out.println("没有找到该元素");
}
}
}
- 二分法查找
//所查找的元素必须有序
public class Array{
public static void main(String[] args){
int[] array1=new int[]{1,2,3,4,5,6,7,8,9};
int cha=5;
int head=0;//初始的首索引
int end =array1.length - 1;//初始的末索引
boolean isFlag=ture;
while(head <= end){
int middle = (head + end)/2;
if(cha==array1[middle]){
System.out.println("找到该元素,位置为:"+middle);
isFlag=false;
break;}
else if (array1[middle]>cha){
end = midddle-1;
}else {//即array1[middle]<cha
head = middle-1;}
}
}
}
if(isFlag){
System.out.println("没有找到该元素");
}