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

前端 未结 3 1349
孤独总比滥情好
孤独总比滥情好 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 04:06

    If the array is sorted and large, use a binary chop to find the nearest elements:

    var getClosestValues = function(a, x) {
        var lo = -1, hi = a.length;
        while (hi - lo > 1) {
            var mid = Math.round((lo + hi)/2);
            if (a[mid] <= x) {
                lo = mid;
            } else {
                hi = mid;
            }
        }
        if (a[lo] == x) hi = lo;
        return [a[lo], a[hi]];
    }
    

    Otherwise, just scan from one end to the other, keeping track of the nearest values above and below the target. For this algorithm, your version is broken, unfortunately. Here's another version:

    var getClosestValues = function(a, x) {
        var lo, hi;
        for (var i = a.length; i--;) {
            if (a[i] <= x && (lo === undefined || lo < a[i])) lo = a[i];
            if (a[i] >= x && (hi === undefined || hi > a[i])) hi = a[i];
        };
        return [lo, hi];
    }
    

提交回复
热议问题