Advertisement
Guest User

Untitled

a guest
Oct 30th, 2014
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6.  
  7. /**
  8. *
  9. * @author om
  10. */
  11.  
  12. import java.util.ArrayList;
  13. import java.util.Comparator;
  14.  
  15. public class RecursiveBinarySearch2 <T>{
  16.  
  17. public static int recursiveBinarySearch(Comparable[] arr, Comparable val, int fl, int rf)
  18. throws ObjectNotFoundException {
  19. if (fl > rf){
  20. throw new ObjectNotFoundException();
  21. }
  22.  
  23. int guess = (rf - fl)/2 + fl;
  24.  
  25. int relation = val.compareTo(arr[guess]);
  26.  
  27. if(relation < 0){
  28. return recursiveBinarySearch(arr, val, fl, guess--);
  29. }
  30.  
  31. if(relation > 0){
  32. return recursiveBinarySearch(arr, val, guess++, rf);
  33. }
  34.  
  35. return guess;
  36. }
  37.  
  38. public static int recursiveBinarySearch(ArrayList<Comparable> al, Comparable val, int fl, int rf)
  39. throws ObjectNotFoundException{
  40. Comparable[] arr = new Comparable[al.size()];
  41. return recursiveBinarySearch(al.toArray(arr), val, fl, rf);
  42.  
  43. }
  44.  
  45. public static int recursiveBinarySearch(ArrayList<Comparable> al, Comparable val)
  46. throws ObjectNotFoundException{
  47. return recursiveBinarySearch(al, val, 0, al.size());
  48. }
  49.  
  50. public static int recursiveBinarySearch(Comparable[] arr, Comparable val)
  51. throws ObjectNotFoundException{
  52. return recursiveBinarySearch(arr, val, 0, arr.length);
  53. }
  54.  
  55. public int recursiveBinarySearch(T[] arr, T val, Comparator<T> cmp, int fl, int rf)
  56. throws ObjectNotFoundException {
  57. if (fl > rf){
  58. throw new ObjectNotFoundException();
  59. }
  60.  
  61. int guess = (rf - fl)/2 + fl;
  62.  
  63. int relation = cmp.compare(val, arr[guess]);
  64.  
  65. if(relation < 0){
  66. return recursiveBinarySearch(arr, val, cmp, fl, guess--);
  67. }
  68.  
  69. if(relation > 0){
  70. return recursiveBinarySearch(arr, val, cmp, guess++, rf);
  71. }
  72.  
  73. return guess;
  74. }
  75.  
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement