Created
July 22, 2014 03:12
-
-
Save pavelnganpi/432286ad64f58105b10b to your computer and use it in GitHub Desktop.
Find k closest elements to a given value Given a sorted array arr[] and a value X, find the k closest elements to X in arr[]. Examples: Input: K = 4, X = 35 arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56} Output: 30 39 42 45
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
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