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);
        }
    }
}

========================================
欢迎各位参考。 有错误或有更好的题目答案可以联系修改。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值