Q:

Given a sorted array of N integers and an integer K. You have to find the top 5 elements from an array which are closest to integer K javascript

<?php 
// PHP Program to Find k closest  
// elements to a given value 
  
/* Function to find the cross  
   over point (the point before 
   which elements are smaller  
   than or equal to x and after 
   which greater than x) */
function findCrossOver($arr, $low,  
                       $high, $x) 
{ 
      
    // Base cases 
      
    // x is greater than all 
    if ($arr[$high] <= $x)  
        return $high; 
          
    // x is smaller than all 
    if ($arr[$low] > $x)  
        return $low; 
      
    // Find the middle point 
    /* low + (high - low)/2 */
    $mid = ($low + $high)/2;  
      
    /* If x is same as middle  
       element, then return mid */
    if ($arr[$mid] <= $x and
        $arr[$mid + 1] > $x) 
        return $mid; 
      
    /* If x is greater than arr[mid],  
       then either arr[mid + 1] is  
       ceiling of x or ceiling lies  
       in arr[mid+1...high] */
    if($arr[$mid] < $x) 
        return findCrossOver($arr, $mid + 1,  
                                 $high, $x); 
      
    return findCrossOver($arr, $low, 
                      $mid - 1, $x); 
} 
  
// This function prints k 
// closest elements to x in arr[]. 
// n is the number of elements  
// in arr[] 
function printKclosest($arr, $x, $k, $n) 
{ 
      
    // Find the crossover point 
    $l = findCrossOver($arr, 0, $n - 1, $x); 
      
    // Right index to search 
    $r = $l + 1; 
      
    // To keep track of count of 
    // elements already printed 
    $count = 0;  
  
    // If x is present in arr[],  
    // then reduce left index 
    // Assumption: all elements  
    // in arr[] are distinct 
    if ($arr[$l] == $x) $l--; 
  
    // Compare elements on left  
    // and right of crossover 
    // point to find the k  
    // closest elements 
    while ($l >= 0 and $r < $n 
              and $count < $k) 
    { 
        if ($x - $arr[$l] < $arr[$r] - $x) 
            echo $arr[$l--]," "; 
        else
            echo $arr[$r++]," "; 
        $count++; 
    } 
  
    // If there are no more 
    // elements on right side, 
    // then print left elements 
    while ($count < $k and $l >= 0) 
        echo $arr[$l--]," "; $count++; 
  
    // If there are no more  
    // elements on left side,  
    // then print right elements 
    while ($count < $k and $r < $n) 
        echo $arr[$r++]; $count++; 
} 
  
// Driver Code 
$arr =array(12, 16, 22, 30, 35, 39, 42, 
                45, 48, 50, 53, 55, 56); 
$n = count($arr); 
$x = 35; $k = 4; 
  
printKclosest($arr, $x, 4, $n); 
  
// This code is contributed by anuj_67. 
?> 
0

New to Communities?

Join the community