当前位置:网站首页>Binary lookup array subscript

Binary lookup array subscript

2022-06-24 23:22:00 Programmer Jiuan

Find array subscript , Indexes , Two points

Binary lookup array , Arrays must be ordered

In order from small to large

import java.util.Arrays;
public class ErFentest {
    
    public static void main(String[] args) {
    
        // Binary lookup array ,, Arrays must be sorted from small to large 
        int index = f(4);// look for 14 The index of 
        System.out.println(index);// Print 14 The index of 
    }
    public static int f(int args) {
    
        int[] a = {
    1,4,8,12,20,24};
        int s = 0;// Start index 
        int e = a.length - 1;// End index 
        while (s <= e) {
    
            int m = (s + e) / 2;// Take the middle number index 
            if (a[m] == args) {
    
                return m;// Return the index of the number 
            } else if (a[m] > args) {
    
                e = m - 1;
            } else {
    
                s = m + 1;
            }

        }
        return -1;// Not returning -1

    }
}
原网站

版权声明
本文为[Programmer Jiuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241745464635.html