入门级的二分查找,查找索引,通俗易懂

折半查找(又称二分查找)

判定树

在这里插入图片描述

简单功能代码实现
  • 二分查找

    就是递归,一半一半查,逐渐缩小范围直到找到需要的索引返回


public class HalfSearch {
    public static void main(String[] args) {
        int[] arr = new int[]{12,23,34,54,56,67,78,98};
        int i = Binary_Search(arr, 78);
        System.out.println(i);
    }
    public static int Binary_Search(int arr[],int value){
        int low=0,high=arr.length-1,mid;
        while(low<high){
            mid=(high+low)/2;
            if(arr[mid]==value){
                return mid;
            }else if(arr[mid]>value){
                high=mid-1;
            }else{
                low=mid+1;
            }
        }
        return -1;
    }
}
  • 查找集合中第二大的数
    就是依次比较,先和最大数进行比较,如果大于最大数,那么将其赋予最大数,最大数赋予第二大的数,循环完毕即可
//查找数组中,第二大的数
public class SecondMax {
    public static void main(String[] args) {
        int[] arr = new int[]{2,35,21,34,546,23,76,3,1,5};
        System.out.println(find_sec_max(arr, arr.length));
    }
    public static int find_sec_max(int data[],int count){
        int MINNUMBER = -32767;

        int maxnumber = data[0];
        int sec_max = MINNUMBER;
        for(int i = 0; i< count;i++){
            if(data[i]>maxnumber){
                sec_max=maxnumber;
                maxnumber=data[i];
            }else{
                if(data[i]>sec_max){
                    sec_max=data[i];
                }
            }
        }
        return sec_max;
    }
}

  • 查找指定数的索引
    循环遍历一一比较直到找到对应索引将其返回。
public class searchNR {
    public static void main(String[] args) {
        int[] arr = {7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
        System.out.println(search(arr, 1));
    }
    public static int search(int a[],int x){
        int i=0;
        while(i<a.length){
            if(x==a[i]){
                return i;
            }
            i++;
        }
        return -1;
    }
}

相关习题:做完肯定有提升
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值