Input entry decision queue value

I want to use binary search in an input pass through column to find the closest value,

and calculated to the nearest number in input, how can it be realized?

the default column is [4, 7, 8] enter 5 in input and he will automatically change to 4.

ask for help!


/ / binary search
Array.prototype.binary_search = function (low, high, khey) {
if (low > high)
return-1;
var mid = parseInt ((high + low) / 2);
if (this [mid] > khey)
return this.binary_search (low, mid-1, khey);
if (this [mid] < khey)
return this.binary_search (mid + 1, high, khey);
return mid;
};

Aug.18,2021


Array.prototype.binary_search_clo = function(khey) {
    var low = 0;
    var high = this.length
    var mid = parseInt((high + low + 1) / 2);
    
    while (this[mid] != khey && low < high){
        if (this[mid] > khey){
            high = mid - 1;
        }
        else if (this[mid] < khey){
            low = mid + 1;
        }
        mid = parseInt((high + low) / 2);
    }
    if (mid > 0 && Math.abs(parseInt(this[mid] - khey)) > Math.abs(parseInt(this[mid-1] - khey))){
        mid = mid -1;
    }
    return mid;
};

found the last, to compare with the side, which is closer.

Menu