How to Efficiently Find the Closest Value in an Ordered Array?

Barbara Streisand
Release: 2024-11-25 18:06:11
Original
182 people have browsed it

How to Efficiently Find the Closest Value in an Ordered Array?

Finding the Closest Value in an Array

In data processing, finding the closest matching value in an array is often essential for various applications. Given a target value and an ordered array, how do we efficiently locate the element closest to the target?

Solution:

To find the closest value in an array, we can iterate through each element in the array and calculate the difference between the target value and each element. The element with the smallest difference is the closest matching value. Here's a PHP function for this task:

function getClosest($search, $arr) {
   $closest = null;
   foreach ($arr as $item) {
      if ($closest === null || abs($search - $closest) > abs($item - $search)) {
         $closest = $item;
      }
   }
   return $closest;
}
Copy after login

This function takes two parameters: the target value to search for and the array of numbers to search within. It calculates the absolute difference between the target value and each element in the array. The element with the smallest absolute difference is stored in the $closest variable and ultimately returned as the result.

Usage:

Consider the following array:

array(0, 5, 10, 11, 12, 20)
Copy after login

When searching with a target value of 0, the function will return 0. For a target value of 3, the function will return 5. Similarly, for a target value of 14, the function will return 12.

The above is the detailed content of How to Efficiently Find the Closest Value in an Ordered Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template