线性查找:
/**
* 线性查找:顺序查找法;在给定的一列数组中,一个个查询需要的内容。
* 如果找到返回下标,如果没有找到,返回-1.
*/
import java.util.Scanner;
public class LinearSearch {
public static void main(String[] args) {
int[] arr = { 10, 23, 9, 5, 7, 78, 34 };
System.out.println("请输入你需要的数值:");
Scanner sc = new Scanner(System.in);
int temp = sc.nextInt();
// 保存数值的下标
int result = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
result = i + 1;
break;
}
}
if (result == -1) {
System.out.println("您所找的数据" + temp + "在arr数组中未找到!");
} else {
System.out.println("您所找的数据" + temp + "在arr数组中的下标为:" + result);
}
}
}
二分查找
/**
* 二分查找(折半查找):
* 待查询的表为有序表
*/
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
System.out.println("请输入你需要的数值:");
Scanner sc = new Scanner(System.in);
int temp = sc.nextInt();
// 设置左标记为0;右标记为数组长度
int left = 0;
int right = arr.length - 1;
int result = -1;// 找到以后保存下标
while (left <= right) {
// 找到中间值
int half = (left + right) / 2;
// 待查元素与表中间元素相等,返回中间元素下标
if (temp == arr[half]) {
result = half + 1;
break;
}
// 假设你要查找的数值是大于中间值,去掉左边的那一部分
if (temp > arr[half]) {
left = half + 1;
}
// 假设你要查找的数值是小于中间值,去掉右边的那一部分
if (temp < arr[half]) {
right = half - 1;
}
}
if (result == -1) {
System.out.println("您所找的数据" + temp + "在arr数组中未找到!");
} else {
System.out.println("您所找的数据" + temp + "在arr数组中的下标为:" + result);
}
}
}