Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class binarySearch {
  4. public static int bSearch(int[] a, int f) {
  5. int l = 0;
  6. int r = a.length-1;
  7. if ( a[0] > f){
  8. return a[0];
  9. }
  10. while (l < r - 1) {
  11. int m = (l + r) / 2;
  12. if (a[m] <= f) {
  13. l = m;
  14. } else {
  15. r = m;
  16. }
  17. }
  18. if (Math.abs(f-a[l]) > Math.abs(f-a[l+1])) {
  19. return a[l+1];
  20. }
  21. return a[l];
  22. }
  23. public static void main(String[] args) {
  24. Scanner scan = new Scanner(System.in);
  25. int n = scan.nextInt();
  26. int k = scan.nextInt();
  27. int[] arrSorted = new int[n];
  28. int[] requests = new int[k];
  29. for (int i = 0; i < n; i++) {
  30. arrSorted[i] = scan.nextInt();
  31. }
  32. for (int i = 0; i < k; i++) {
  33. requests[i] = scan.nextInt();
  34. }
  35. for (int i = 0; i < k; i++) {
  36. System.out.println(bSearch(arrSorted, requests[i]));
  37. }
  38.  
  39. }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement