Formal way of getting closest values in array in Javascript, given a value and a sorted array?

前端 未结 3 1350
孤独总比滥情好
孤独总比滥情好 2020-12-08 03:37

If I have an array like this:

var array = [1, 3, 4, 5, 9, 10];

And I have a value like this:

var value = 8;
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 03:57

    For array with sorted values (data is a matrix, xIndex is the column to search, xVal is the value to sarch for, threshold is the tolerated distance (maybe 0) ):

    public static int getNearestValueIndex(double[][] data, int xIndex, Number xVal, int threshold){
        int indexMin = 0;
        int indexMax=data.length-1;
    
        int index;
        double val;
        double valToFind=xVal.doubleValue();
        double diff;
        index = (indexMax+indexMin)/2;
        while(index!=indexMin){
    
            val = data[index][xIndex];
            diff = Math.abs(valToFind-val);
            if(diff<=threshold) break;
    
            if(valxVal.doubleValue()){
                indexMax=index;
            }
            index = (indexMax+indexMin)/2;
        }
        val = data[index][xIndex];
        if(data.length>(index+1) && Math.abs(valToFind-val)> Math.abs(valToFind-data[index+1][xIndex])){
            index=index+1;
        }
    
        return index;
    }
    

提交回复
热议问题