Java经典算法搜索
目录
Java经典算法:搜索
1.无序数组中搜索元素
假如:定义一个数组:int[] arr = {18, 52, 7, 44, 16, 68, 92, 35, 50};
在数组中搜索元素search=44
如果找到,打印出该元素在数组中的下标
如果找不到,打印出-1
思路:
要搜索的数与数组中第1个元素比较,相等输出下标,不相等继续
要搜索的数与数组中第2个元素比较,相等输出下标,不相等继续
要搜索的数与数组中第3个元素比较,相等输出下标,不相等继续
…………………………
要搜索的数与数组中第arr.length-1个元素比较,相等输出下标,不相等输出-1
public class search {
public static void main(String[] args) {
// 定义数组
int[] arr = { 18, 52, 7, 44, 16, 68, 92, 35, 50 };
int search = 51;
boolean find = false; // 找到则为true 没找到则为false
// 在数组中搜索元素
// 如果找到,打印出该元素在数组中的下标
// 如果找不到,打印出-1
for (int i = 0; i < arr.length; i++) {
if (search == arr[i]) {
System.out.println(i);
find = true;
break;
}
}
// 判断是否找到,如果没找到,则输出-1
if (!find) {
System.out.println(-1);
}
}
}
2.有序数组中搜索元素
假如:定义一个数组:int[] arr = {7,16,18,35,44,50,52,68,92};
当数组中元素已经按照从小到大排序好了,要求
在数组中搜索元素search=44
如果找到,打印出该元素在数组中的下标
如果找不到,打印出-1
注意:此时如果再一个一个搜索,效率就有点慢了,有没有更好更快速的搜索方法?
public class Search1 {
public static void main(String[] args) {
// 定义数组(已经按照从小到大排序好了)
int[] arr = { 7, 16, 18, 35, 44, 50, 52, 68, 92 };
int search = 44;
boolean find = false; // 找到则为true 没找到则为false
// 在数组中搜索元素
// 如果找到,打印出该元素在数组中的下标
// 如果找不到,打印出-1
// 定义左边界和右边界
int min = 0;
int max = arr.length - 1;
// 循环,不断从min和max的中间搜索
do {
int test = (max + min) / 2;
if (arr[test] == search) { // 找到了
System.out.println(test);
find = true;
break;
} else if (arr[test] > search) { // 在左边继续搜索
max = test - 1;
} else { // 在右边继续搜索
min = test + 1;
}
// 找不到,退出循环的条件
if (min > max) {
break;
}
} while (true);
// 判断是否找到,找不到则需要输出-1
if (!find) {
System.out.println(-1);
}
}
}
========================================
欢迎各位参考。 有错误或有更好的题目答案可以联系修改。