当前位置:网站首页>二分查找数组下标

二分查找数组下标

2022-06-24 19:42:00 程序员久安

查找数组下标,索引,二分

二分查找数组,数组必须是有序的

按照从小到大排序

import java.util.Arrays;
public class ErFentest {
    
    public static void main(String[] args) {
    
        //二分查找数组,,数组必须按照从小到大排序
        int index = f(4);//找14的索引
        System.out.println(index);//打印14的索引
    }
    public static int f(int args) {
    
        int[] a = {
    1,4,8,12,20,24};
        int s = 0;//开始索引
        int e = a.length - 1;//结束索引
        while (s <= e) {
    
            int m = (s + e) / 2;//取中间数字索引
            if (a[m] == args) {
    
                return m;//返回该数索引
            } else if (a[m] > args) {
    
                e = m - 1;
            } else {
    
                s = m + 1;
            }

        }
        return -1;//不在返回-1

    }
}
原网站

版权声明
本文为[程序员久安]所创,转载请带上原文链接,感谢
https://withk.blog.csdn.net/article/details/116428596