C++ Program to Find closest number in array
Last Updated :
03 Apr, 2023
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 absolute difference of current element with every element. Finally return the element that has minimum absolution difference.
An efficient solution is to use Binary Search.
C++
// CPP program to find element
// closest to given target.
#include <bits/stdc++.h>
using namespace std;
int getClosest(int, int, int);
// Returns element closest to target in arr[]
int findClosest(int arr[], int n, int target)
{
// Corner cases
if (target <= arr[0])
return arr[0];
if (target >= arr[n - 1])
return arr[n - 1];
// Doing binary search
int 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.
int getClosest(int val1, int val2,
int target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int target = 11;
cout << (findClosest(arr, n, target));
}
// This code is contributed by Smitha Dinesh Semwal
Output:
9
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:
C++
// CPP program to find element
// closest to given target using two pointers
#include <bits/stdc++.h>
using namespace std;
int findClosest(int arr[], int n, int target)
{
int left = 0, right = n - 1;
while (left < right) {
if (abs(arr[left] - target)
<= abs(arr[right] - target)) {
right--;
}
else {
left++;
}
}
return arr[left];
}
int main()
{
int arr[] = { 1, 2, 4, 5, 6, 6, 8, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int target = 11;
cout << findClosest(arr, n, target);
return 0;
}
// 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
C++ Program to Find the Second Largest Element in an Array In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
3 min read
C++ Program to Find the Minimum and Maximum Element of an Array Given an array, write functions to find the minimum and maximum elements in it. Example: C++ // C++ program to find minimum (or maximum) element // in an array. #include <bits/stdc++.h> using namespace std; int getMin(int arr[], int n) { int res = arr[0]; for (int i = 1; i < n; i++) res =
3 min read
How to Find the Smallest Number in an Array in C++? In C++, arrays are the data types that store the collection of the elements of other data types such as int, float, etc. In this article, we will learn how to find the smallest number in an array using C++. For Example,Input: myVector = {10, 3, 10, 7, 1, 5, 4} Output: Smallest Number = 1Find the Sma
2 min read
C++ Program to Find Index of First Occurrence of a Value in Array In C++, an array is a data structure that stores elements of the same type in contiguous memory locations. In this article, we will learn how to find the index of the first occurrence of a specific value in an array in C++. Example: Input: int arr[] = {5, 7, 1, 2, 3, 7, 1} Target = 1Output: The firs
2 min read
How to Find All Indexes of an Element in an Array in C++? In C++, an array is a collection of elements of the same type placed in contiguous memory locations. In this article, we will learn how to find all indexes of a specific element in an array in C++. Example: Input: myArray = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4}; target = 3Output: The element 3 occurred at
2 min read
How to Find the Second Smallest Element in an Array in C++? In C++, arrays are data structures that store the collection of data elements of the same type in contiguous memory locations. In this article, we will learn how to find the second smallest element in an array in C++. Example:Input:myArray = {10, 5, 8, 2, 7, 3, 15};Output:The second smallest element
3 min read
How to Find the Minimum Element in a List in C++? In C++, a list is a sequence container provided by the STL library that stores data in non-contiguous memory locations efficiently. In this article, we will learn how to find the minimum element in a list in C++. Example: Input: myList = {30, 10, 20, 50, 40};Output: The minimum element in the list i
2 min read
Nearest smaller character to a character K from a Sorted Array Given a sorted array of characters arr[] and a character K, the task is to find the character with nearest smaller ASCII value than K from the given array. Print -1 if no character is found to be having smaller ASCII value than K.Examples: Input: arr[] = {'e', 'g', 't', 'y'}, K = 'u' Output: t Expla
6 min read
Queries to find the minimum index in given array having at least value X Given an array arr[] of size N and an array Q[] consisting of M integers, each representing a query, the task for each query Q[i] is to find the smallest index of an array element whose value is greater than or equal to Q[i]. If no such index exists, then print -1. Examples: Input: arr[] = { 1, 9 },
9 min read
Minimum change in given value so that it lies in all given Ranges Given an array of ranges arr[] of length N and a number D, the task is to find the minimum amount by which the number D should be changed such that D lies in every range of given array. Here a range consists of two integer [start, end] and D is said to be inside of range, if start ? D ? end. Example
7 min read