Skip to content

Instantly share code, notes, and snippets.

@gabhi
Forked from pavelnganpi/findKCLosestElement.java
Last active August 29, 2015 14:06
Show Gist options
  • Save gabhi/d13dbbe691ad267d1265 to your computer and use it in GitHub Desktop.
Save gabhi/d13dbbe691ad267d1265 to your computer and use it in GitHub Desktop.
Find k closest elements to a given value
public class FindKClosestElementToAGivenValue {
public static int binarySearch(int[] arr,int low, int high, int x){
int mid = 0;
while(low<=high){
mid = (high+low)/2;
if(arr[mid] == x){
return mid;
}
else if(x<arr[mid]){
high = mid-1;
}
else{
low = mid+1;
}
}
return mid;
}
public static void solution(int[] arr,int x, int k){
//crosover point
int cp = binarySearch(arr, 0, arr.length-1, x);
int n = arr.length-1;
int left = cp-1;
int right = cp+1;
int count = 0;
// if(arr[left] == x){
// left--;
// }
while(left>=0 && right<n && count <k){
if(x-arr[left]< arr[right] -x){
System.out.println(arr[left--]);
left--;
}
else{
System.out.println(arr[right++]);
right++;
}
count++;
}
//if right is over, print all left
if(right == n){
while(count<k && left>=0){
System.out.println(arr[left]);
count++;
}
}
//if right is over, print all left
if(left < 0){
while(count<k && left>=0){
System.out.println(arr[right]);
count++;
}
}
}
public static void main(String[]args){
int[] arr = {1,2,3,4,5,6,7};
int k = 4;
int x = 35;
int arr1[] = {12, 16, 22, 30, 35, 39, 42,45, 48, 50, 53, 55, 56};
System.out.println(binarySearch(arr1, 0, arr.length, x));
solution(arr1,x,k);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment