[Java] 纯文本查看 复制代码
import java.util.Scanner;
public class SequentialSearch {
int a[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};
public SequentialSearch(){
System.out.println("请输入要查询的数字:");
Scanner input=new Scanner(System.in);
int input1=input.nextInt();
for(int i=0;i<a.length;i++){
if(a==input1){
System.out.println(input1+"的位置为:"+i);
break;
}
if(i==a.length-1)
System.out.println("No Result!");
}
}
}
[Java] 纯文本查看 复制代码
import java.util.ArrayList;
import java.util.List;
public class binarySearch {
public binarySearch(){
List<Integer> list=new ArrayList<Integer>();
for(int i=0;i<10000;i+=2){ //往list加入逐渐增大1-10000的所有偶数,作为实验数组,很明显,他是有序的!
list.add(i); //这里当然也可用数组
}
int low=0;
int high=list.size();
int key=3334;
while(low<=high){
int mid=(low+high)/2;
if(key==list.get(mid)){
System.out.println("此数值在list中的位置为:"+mid);
break;
}
if(key>list.get(mid)){
low=mid+1; //当小于时,是low指针向后移动,high指针不变
}
if(key<list.get(mid)){
high=mid-1; //当大于时,是high指针向前移动,low指针不变
}
}
if(low>high){
System.out.println("没有查到结果!");
}
}
}