PHP Program to Find closest number in array
Last Updated :
22 Jul, 2024
Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers.
Examples:
Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9}
Target number = 11
Output : 9
9 is closest to 11 in given array
Input : arr[] = {2, 5, 6, 7, 8, 8, 9};
Target number = 4
Output : 5
A simple solution is to traverse through the given array and keep track of the absolute difference of current element with every element. Finally return the element that has minimum absolution difference.
PHP
<?php
// PHP program to find element closest
// to given target.
// Returns element closest to target in arr[]
function findClosest($arr, $n, $target)
{
// Corner cases
if ($target <= $arr[0])
return $arr[0];
if ($target >= $arr[$n - 1])
return $arr[$n - 1];
// Doing binary search
$i = 0;
$j = $n;
$mid = 0;
while ($i < $j)
{
$mid = ($i + $j) / 2;
if ($arr[$mid] == $target)
return $arr[$mid];
/* If target is less than array element,
then search in left */
if ($target < $arr[$mid])
{
// If target is greater than previous
// to mid, return closest of two
if ($mid > 0 && $target > $arr[$mid - 1])
return getClosest($arr[$mid - 1],
$arr[$mid], $target);
/* Repeat for left half */
$j = $mid;
}
// If target is greater than mid
else
{
if ($mid < $n - 1 &&
$target < $arr[$mid + 1])
return getClosest($arr[$mid],
$arr[$mid + 1], $target);
// update i
$i = $mid + 1;
}
}
// Only single element left after search
return $arr[$mid];
}
// Method to compare which one is the more close.
// We find the closest by taking the difference
// between the target and both values. It assumes
// that val2 is greater than val1 and target lies
// between these two.
function getClosest($val1, $val2, $target)
{
if ($target - $val1 >= $val2 - $target)
return $val2;
else
return $val1;
}
// Driver code
$arr = array( 1, 2, 4, 5, 6, 6, 8, 9 );
$n = sizeof($arr);
$target = 11;
echo (findClosest($arr, $n, $target));
// This code is contributed bu Sachin.
?>
Time Complexity: O(log(n))
Auxiliary Space: O(log(n)) (implicit stack is created due to recursion)
Approach 2: Using Two Pointers
Another approach to solve this problem is to use two pointers technique, where we maintain two pointers left and right, and move them towards each other based on their absolute difference with target.
Below are the steps:
- Initialize left = 0 and right = n-1, where n is the size of the array.
- Loop while left < right
- If the absolute difference between arr[left] and target is less than or equal to the absolute difference between arr[right] and target, move left pointer one step to the right, i.e. left++
- Else, move right pointer one step to the left, i.e. right–-
- Return arr[left], which will be the element closest to the target.
Below is the implementation of the above approach:
PHP
<?php
function findClosest($arr, $n, $target) {
$left = 0;
$right = $n - 1;
while ($left < $right) {
if (abs($arr[$left] - $target) <= abs($arr[$right] - $target)) {
$right--;
} else {
$left++;
}
}
return $arr[$left];
}
$arr = array(1, 2, 4, 5, 6, 6, 8, 8, 9);
$n = sizeof($arr);
$target = 11;
echo findClosest($arr, $n, $target);
// This code is contributed by Susobhan Akhuli
?>
Time Complexity: O(N), where n is the length of the array.
Auxiliary Space: O(1)
Please refer complete article on Find closest number in array for more details!
Similar Reads
How to Sort Numeric Array in PHP? Given a numeric array, the task is to sort the numeric array using PHP. There are various built-in functions to sort arrays in different ways. Below are the approaches to sort numeric arrays in PHP:Table of ContentUsing sort() FunctionUsing rsort() FunctionUsing asort() FunctionUsing arsort() Functi
3 min read
PHP Program to Sort an Array in Ascending Order Sorting array elements is a common operation in programming. PHP provides several methods to achieve this operation. In this article, we will explore various approaches to sort array elements of an array in ascending order.Table of ContentUsing sort() FunctionUsing asort() FunctionUsing array_multis
3 min read
PHP Program for Number of local extrema in an array You are given an array on n-elements. An extrema is an element that is either greater than its both of neighbors or less than its both neighbors. You have to calculate the number of local extrema in given array. Note: 1st and last elements are not extrema.Examples : Input : a[] = {1, 5, 2, 5}Output
2 min read
PHP Program to Check for Lucky Numbers We have given an input number, and our task is to check if it is a lucky number or not in PHP based on the criteria that all digits in the number must be different. Examples: Input: n = 7Output: 7 is a lucky numberInput: n = 9Output: 9 is not a lucky numberBelow are the approaches to check for lucky
2 min read
PHP Program to Find Duplicate Elements from an Array Given an array containing some repeated elements, the task is to find the duplicate elements from the given array. If array elements are not repeated, then it returns an empty array.Examples:Input: arr = [1, 2, 3, 6, 3, 6, 1]Output: [1, 3, 6]Input: arr = [3, 5, 2, 5, 3, 9]Output: [3, 5]There are two
6 min read