Closest in Sorted array

Last Updated : 13 Aug, 2026

Given an array arr[] of sorted integers of size n. We need to find the closest value to the given number k. Array may contain duplicate values and negative numbers. If the smallest difference with k is the same for two values in the array return the greater value.

Examples:  

Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9}, k = 11
Output : 9
Explanation : 9 is closest to 11 in given array

Input :arr[] = {2, 5, 6, 7, 8, 8, 9}, k = 4
Output : 5
Explanation: 5 is closest to 4 in given array

Input :arr[] = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32}, k = 17
Output : 19
Explanation : 15 and 19 both are closest to 17 in given array ,so return max(15, 19) which is 19

Try It Yourself
redirect icon

[Naive Approach] - Linear Traversal O(n) Time and O(1) Space

The idea is to go through the given array and check how close each element is to the k by comparing their differences.

We keeps track of the element that is closest to the k.

At first, the result is set to the first element of the array, and with each loop, we updates the result if we finds a closer element.

C++
// C++ program to find closest number in Sorted array

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

int findClosest(const vector<int> &arr, int k) {
    int res = arr[0];
    for (int i = 1; i < arr.size(); i++) {
      
      	// update the result if we finds a closer element.
        if (abs(arr[i] - k) <= abs(res - k)) {
            res = arr[i];
        }
    }
    return res;
}

int main() {
    vector<int> arr = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32};
    int k = 17;
    cout << findClosest(arr, k) << endl;
    return 0;
}
C
// C program to find closest number in a sorted array

#include <stdio.h>
#include <stdlib.h>

int findClosest(int arr[], int n, int k) {
    int res = arr[0];
    for (int i = 1; i < n; i++) {
      
        // update the result if we find a closer element.
        if (abs(arr[i] - k) <= abs(res - k)) {
            res = arr[i];
        }
    }
    return res;
}

int main() {
    int arr[] = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 17;
  
    printf("%d\n", findClosest(arr, n, k));
    return 0;
}
Java
// Java program to find closest number in a sorted array

import java.util.*;

class GfG {

    static int findClosest(int[] arr, int k) {
        int res = arr[0];
        for (int i = 1; i < arr.length; i++) {
          
            // update the result if we find a closer element.
            if (Math.abs(arr[i] - k) <= Math.abs(res - k)) {
                res = arr[i];
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32};
        int k = 17;
        System.out.println(findClosest(arr, k));
    }
}
Python
# Python program to find closest number in a sorted array

def findClosest(arr, k):
    res = arr[0]
    for i in range(1, len(arr)):
      
        # update the result if we find a closer element.
        if abs(arr[i] - k) <= abs(res - k):
            res = arr[i]
    return res

if __name__ == "__main__":
    arr = [2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32]
    k = 17
    print(findClosest(arr, k))
C#
// C# program to find closest number in a sorted array

using System;

class GfG {
    static int findClosest(int[] arr, int k) {
        int res = arr[0];
        for (int i = 1; i < arr.Length; i++) {
          
            // update the result if we find a closer element.
            if (Math.Abs(arr[i] - k) <= Math.Abs(res - k)) {
                res = arr[i];
            }
        }
        return res;
    }

    static void Main(string[] args) {
        int[] arr = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32};
        int k = 17;
        Console.WriteLine(findClosest(arr, k));
    }
}
JavaScript
// JavaScript program to find closest number in a sorted array

function findClosest(arr, k) {
    let res = arr[0];
    for (let i = 1; i < arr.length; i++) {
      
        // update the result if we find a closer element.
        if (Math.abs(arr[i] - k) <= Math.abs(res - k)) {
            res = arr[i];
        }
    }
    return res;
}

let arr = [2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32];
let k = 17;
console.log(findClosest(arr, k));

Output
19

[Better Approach] - Traverse till First Greater - O(n) Time and O(1) Space

The idea is to go through the array until we finds the first element that is greater than or equal to k.

If no such element is found, meaning all elements are smaller, we return the last element of the array.

If we finds such an element, we checks which one is closer to the k by comparing it with the previous element.

C++
// C++ program to find closest number in Sorted array

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

int findClosest(vector<int> &arr, int k) {
    int n = arr.size();

    // Find the first larger element of k in arr
    int i;
    for (i = 1; i < n; i++) {
        if (arr[i] >= k)
            break;
    }

    // If all elements are smaller, return the last element
    if (i == n) {
        return arr[n - 1];
    }

    // Check the current and previous element for closest
    if ((arr[i] - k) <= k - arr[i - 1])
        return arr[i];
    else
        return arr[i - 1];
}

int main() {
    vector<int> arr = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32};
    int k = 17;
    cout << findClosest(arr, k) << endl;
    return 0;
}
C
// C program to find closest number in a sorted array

#include <stdio.h>

int findClosest(int arr[], int n, int k) {
    int i;
    
    // Find the first larger element of k in arr
    for (i = 1; i < n; i++) {
        if (arr[i] >= k) break;
    }
    
    // If all elements are smaller, return the last element
    if (i == n) {
        return arr[n-1];
    }
  
    // Check the current and previous element for closest
    if ((arr[i] - k) <= k - arr[i-1])
        return arr[i];
    else
        return arr[i-1];
}

int main() {
    int arr[] = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 17;    
  	
    printf("%d\n", findClosest(arr, n, k));
    return 0;
}
Java
// Java program to find closest number in a sorted array

class GfG {
    static int findClosest(int[] arr, int k) {
        int n = arr.length;
        int i;
        
        // Find the first larger element of k in arr
        for (i = 1; i < n; i++) {
            if (arr[i] >= k) break;
        }
        
        // If all elements are smaller, return the last element
        if (i == n) {
            return arr[n-1];
        }
      
        // Check the current and previous element for closest
        if ((arr[i] - k) <= k - arr[i-1])
            return arr[i];
        else
            return arr[i-1];
    }

    public static void main(String[] args) {
        int[] arr = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32};
        int k = 17;    
      
        System.out.println(findClosest(arr, k));
    }
}
Python
# Python program to find closest number in a sorted array

def findClosest(arr, k):
    n = len(arr)
    i = 0
    
    # Find the first larger element of k in arr
    for i in range(1, n):
        if arr[i] >= k:
            break
    
    # If all elements are smaller, return the last element
    if i == n:
        return arr[n-1]
  
    # Check the current and previous element for closest
    if (arr[i] - k) <= k - arr[i-1]:
        return arr[i]
    else:
        return arr[i-1]

if __name__ == "__main__":
    arr = [2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32]
    k = 17    
    print(findClosest(arr, k))
C#
// C# program to find closest number in a sorted array

using System;

class GfG {
    static int findClosest(int[] arr, int k) {
        int n = arr.Length;
        int i;

        // Find the first larger element of k in arr
        for (i = 1; i < n; i++) {
            if (arr[i] >= k) break;
        }

        // If all elements are smaller, return the last element
        if (i == n) {
            return arr[n-1];
        }
      
        // Check the current and previous element for closest
        if ((arr[i] - k) <= k - arr[i-1])
            return arr[i];
        else
            return arr[i-1];
    }

    static void Main(string[] args) {
        int[] arr = {2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32};
        int k = 17;    
        Console.WriteLine(findClosest(arr, k));
    }
}
JavaScript
// JavaScript program to find closest number in a sorted array

function findClosest(arr, k) {
    let n = arr.length;
    let i;

    // Find the first larger element of k in arr
    for (i = 1; i < n; i++) {
        if (arr[i] >= k) break;
    }

    // If all elements are smaller, return the last element
    if (i === n) {
        return arr[n - 1];
    }
  
    // Check the current and previous element for closest
    if ((arr[i] - k) <= k - arr[i - 1]) {
        return arr[i];
    } else {
        return arr[i - 1];
    }
}

let arr = [2, 5, 6, 7, 8, 8, 9, 15, 19, 22, 32];
let k = 17;    
console.log(findClosest(arr, k));

Output
19

[Expected Approach] Binary Search - O(Log n) Time and O(1) Space

The approach is to use binary search to find the element in a sorted array that is closest to the k.

We start by setting the result to the first element. Then, using two pointers lo and hi, we repeatedly narrow down the search space until we find the closest element.

At each step, we compare the middle element mid with the k.

If it's closer than the current result, we update result. If there's a tie, the larger value is chosen. If we find the exact k, we return it right away. Otherwise, the search continues, and the closest value is returned at the end.

C++
// C++ program to find closest number in Sorted array

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

int findClosest(vector<int> &arr, int k) {
    int res = arr[0];
    int lo = 0, hi = arr.size() - 1;

    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;

        // Update res if mid is closer to k
        if (abs(arr[mid] - k) < abs(res - k)) {
            res = arr[mid];

            // In case of a tie, prefer larger value
        }
        else if (abs(arr[mid] - k) == abs(res - k)) {
            res = max(res, arr[mid]);
        }

        if (arr[mid] == k) {
            return arr[mid];
        }
        else if (arr[mid] < k) {
            lo = mid + 1;
        }
        else {
            hi = mid - 1;
        }
    }

    return res;
}

int main() {
    vector<int> arr = {1, 2, 4, 5, 6, 6, 8, 8, 9};
    int k = 11;
  
    cout << findClosest(arr, k) << endl;
    return 0;
}
C
// C program to find closest number in a sorted array

#include <stdio.h>
#include <stdlib.h>

int findClosest(int arr[], int n, int k) {
    int res = arr[0];
    int lo = 0, hi = n - 1;

    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;

        // Update res if mid is closer to k
        if (abs(arr[mid] - k) < abs(res - k)) {
            res = arr[mid];

            // In case of a tie, prefer larger value
        }
        else if (abs(arr[mid] - k) == abs(res - k)) {
            res = (res > arr[mid]) ? res : arr[mid];
        }

        if (arr[mid] == k) {
            return arr[mid];
        }
        else if (arr[mid] < k) {
            lo = mid + 1;
        }
        else {
            hi = mid - 1;
        }
    }
    return res;
}

int main() {
    int arr[] = {1, 2, 4, 5, 6, 6, 8, 8, 9};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 11;

    printf("%d\n", findClosest(arr, n, k));
    return 0;
}
Java
// Java program to find closest number in a sorted array

class GfG {
    static int findClosest(int[] arr, int k) {
        int res = arr[0];
        int lo = 0, hi = arr.length - 1;

        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;

            // Update res if mid is closer to k
            if (Math.abs(arr[mid] - k) < Math.abs(res - k)) {
                res = arr[mid];

            // In case of a tie, prefer larger value
            } else if (Math.abs(arr[mid] - k) == Math.abs(res - k)) {
                res = Math.max(res, arr[mid]);
            }

            if (arr[mid] == k) {
                return arr[mid];
            } else if (arr[mid] < k) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 4, 5, 6, 6, 8, 8, 9};
        int k = 11;

        System.out.println(findClosest(arr, k));
    }
}
Python
# Python program to find closest number in a sorted array

def findClosest(arr, k):
    res = arr[0]
    lo = 0
    hi = len(arr) - 1

    while lo <= hi:
        mid = lo + (hi - lo) // 2

        # Update res if mid is closer to k
        if abs(arr[mid] - k) < abs(res - k):
            res = arr[mid]

        # In case of a tie, prefer larger value
        elif abs(arr[mid] - k) == abs(res - k):
            res = max(res, arr[mid])

        if arr[mid] == k:
            return arr[mid]
        elif arr[mid] < k:
            lo = mid + 1
        else:
            hi = mid - 1

    return res

if __name__ == "__main__":
    arr = [1, 2, 4, 5, 6, 6, 8, 8, 9]
    k = 11

    print(findClosest(arr, k))
C#
// C# program to find closest number in a sorted array

using System;

class GfG {
    static int findClosest(int[] arr, int k) {
        int res = arr[0];
        int lo = 0, hi = arr.Length - 1;

        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;

            // Update res if mid is closer to k
            if (Math.Abs(arr[mid] - k) < Math.Abs(res - k)) {
                res = arr[mid];

                // In case of a tie, prefer larger value
            } else if (Math.Abs(arr[mid] - k) == Math.Abs(res - k)) {
                res = Math.Max(res, arr[mid]);
            }

            if (arr[mid] == k) {
                return arr[mid];
            } else if (arr[mid] < k) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }

        return res;
    }

    static void Main(string[] args) {
        int[] arr = {1, 2, 4, 5, 6, 6, 8, 8, 9};
        int k = 11;

        Console.WriteLine(findClosest(arr, k));
    }
}
JavaScript
// JavaScript program to find closest number in a sorted array

function findClosest(arr, k) {
    let res = arr[0];
    let lo = 0, hi = arr.length - 1;

    while (lo <= hi) {
        let mid = lo + Math.floor((hi - lo) / 2);

        // Update res if mid is closer to k
        if (Math.abs(arr[mid] - k) < Math.abs(res - k)) {
            res = arr[mid];

        // In case of a tie, prefer larger value
        } else if (Math.abs(arr[mid] - k) === Math.abs(res - k)) {
            res = Math.max(res, arr[mid]);
        }

        if (arr[mid] === k) {
            return arr[mid];
        } else if (arr[mid] < k) {
            lo = mid + 1;
        } else {
            hi = mid - 1;
        }
    }
    return res;
}

let arr = [1, 2, 4, 5, 6, 6, 8, 8, 9];
let k = 11;

console.log(findClosest(arr, k));

Output
9


Comment