顺序查找
package day08;
import java.util.Scanner;
public class Search01 {
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6};
Scanner input = new Scanner(System.in);
System.out.println("输入你要查找的数");
int n = input.nextInt();
boolean temp = false;
for(int b:a) {
if(b == n) {
temp = true;
}
}
if(temp==true) {
System.out.println("找的到");
}else {
System.out.println("找不到");
}
}
}
二分查找
package day08;
import java.util.Scanner;
public class Search02 {
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6,7,8};
Scanner input = new Scanner(System.in);
System.out.println("输入你要查找的数");
int n = input.nextInt();
int len = a.length;
int s = 0;
int e = len-1;
boolean temp = false;
while(s<=e){
int t = (s+e)/2;
if(n==a[t]) {
temp = true;
break;
}else if(n>a[t]) {
s = t+1;
}else {
e = t-1;
}
}
if(temp==true) {
System.out.println("找到了");
}else {
System.out.println("找不到");
}
}
}