How to find the k closest elements to a giving value in sorted array with PHP

1 Answer

0 votes
function findKClosestElements(&$arr, $k, $value) {
    $left = 0;
    $right = count($arr) - 1;
    
    while ($right - $left >= $k) {
        if (abs($arr[$left] - $value) > abs($arr[$right] - $value)) {
            $left++;
        }
        else {
            $right--;
        }
    }
    
    while ($left <= $right) {
        echo $arr[$left] . " ";
        $left++;
    }
}
        
$arr = array(6, 10, 12, 15, 17, 18, 20, 25, 28);
$value = 16;
$k = 4;

findKClosestElements($arr, $k, $value);




 
/*
run:
 
12 15 17 18 
 
*/

 



answered Jan 21, 2024 by avibootz
...