
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find closest number in array in C++
Suppose we have an array A with n elements. And elements are sorted. We have to find the closest value to the given integer. The array may contain duplicate values and negative numbers. So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5.
We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.
Example
#include<iostream> #include<list> using namespace std; int getNearest(int x, int y, int target) { if (target - x >= y - target) return y; else return x; } int getNearestElement(int arr[], int n, int target) { if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; int left = 0, right = n, mid = 0; while (left < right) { mid = (left + right) / 2; if (arr[mid] == target) return arr[mid]; if (target < arr[mid]) { if (mid > 0 && target > arr[mid - 1]) return getNearest(arr[mid - 1], arr[mid], target); right = mid; } else { if (mid < n - 1 && target < arr[mid + 1]) return getNearest(arr[mid], arr[mid + 1], target); left = mid + 1; } } return arr[mid]; } int main() { int arr[] = { 2, 5, 6, 7, 8, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int target = 4; cout << "Nearest element of " << target << " is: " << getNearestElement(arr, n, target); }
Output
Nearest element of 4 is: 5
- Related Articles
- JavaScript Program to Find closest number in array
- Find closest value for every element in array in C++
- Find k closest numbers in an unsorted array in C++
- Find the closest and smaller tidy number in C++
- Find closest greater value for every element in array in C++
- Find closest smaller value for every element in array in C++
- Find closest index of array in JavaScript
- C++ Program to Find Closest Pair of Points in an Array
- Find K Closest Elements in C++
- Find the Closest Palindrome in C++
- Get the closest number out of an array in JavaScript
- Find the number closest to n and divisible by m in C++
- Get closest number out of array JavaScript
- Find the closest value of an array in JavaScript
- Sum of Mutated Array Closest to Target in C++

Advertisements