1、查找
package cn.edu.csdn.net;
import java.util.Scanner;
public class Find {
public static void main(String[] args) {
int[] arr={3,4,5,7,6,8,9};
System.out.println("请输入:");
Scanner in=new Scanner(System.in);
int num1=in.nextInt();
int num=getIndex(arr,num1);
System.out.println("find="+num);
}
public static int getIndex(int[] arr,int key){
for (int i = 0; i < arr.length; i++) {
if(arr[i]==key)
return i;
}
return-1;
}
}
2、折半查找
package cn.edu.csdn.net;
import java.util.Scanner;
public class ArrayTest {
public static int halfSearch(int[] arr,int key){
int min, max,mid;
min=0;
max=arr.length-1;
mid=(max+min)/2;
while(arr[mid]!=key){
if(key>arr[mid])
min=mid+1;
else if(key<arr[mid])
max=mid-1;
if(min>max)
return-1;
mid=(max+min)/2;
}
return mid;
}
public static void main(String[] args) {
int[] arr={0,1,2,3,4,6,8,9};
System.out.println("请输入数字:");
Scanner in=new Scanner(System.in);
int num=in.nextInt();
int index=halfSearch(arr,num);
System.out.println("intdex="+index);
}
}