Guest User

Untitled

a guest
May 20th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. package binary_search;
  2.  
  3. public class binary_search
  4. {
  5.  
  6. public static void main(String[] args)
  7. {
  8. int[] arr = new int[20];
  9. for (int i = 0; i < 20; i++)
  10. {
  11. arr[i] = i + 1;
  12. }
  13.  
  14. int index = search(arr, 17);
  15. System.out.println(index);
  16. }
  17.  
  18. // Just a wrapper to the binary search.
  19. private static int search(int[] arr, int value)
  20. {
  21. return binarySearch(arr, 0, arr.length - 1, value);
  22. }
  23.  
  24. /**
  25. * Recursive implementation of binary search in a integer array. Search has a
  26. * O(log n) time complexity.
  27. *
  28. * @param arr
  29. * @param low
  30. * @param high
  31. * @param value
  32. * @return
  33. */
  34. private static int binarySearch(int[] arr, int low, int high, int value)
  35. {
  36. int mid = low + (high - low) / 2;
  37. if (arr[mid] == value)
  38. {
  39. return mid;
  40. }
  41.  
  42. // If the value is less than the mid point search the first half
  43. if (arr[mid] > value)
  44. {
  45. return binarySearch(arr, low, mid - 1, value);
  46. }
  47. // If the value is greater than the mid point than search the last half of the
  48. // array.
  49. if (arr[mid] < value)
  50. {
  51. return binarySearch(arr, mid + 1, high, value);
  52. }
  53.  
  54. // If it isn't in the arr return -1
  55. return -1;
  56. }
  57.  
  58. }
Add Comment
Please, Sign In to add comment