Advertisement
Guest User

fffff

a guest
Feb 19th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1.  
  2. class stringSearch {
  3.  
  4.  
  5. static int binarySearch(String[] arr, String x)
  6. {
  7. int l = 0, r = arr.length - 1;
  8. while (l <= r) {
  9. int m = l + (r - l) / 2;
  10.  
  11. int res = x.compareTo(arr[m]);
  12.  
  13. // prüfen ob x in der Mitte
  14. if (res == 0)
  15. return m;
  16.  
  17. // If x größer, linke Hälfte ignorieren
  18. if (res > 0)
  19. l = m + 1;
  20.  
  21. // If x ist kleiner, rechte Hälfte ignorieren
  22. else
  23. r = m - 1;
  24. }
  25.  
  26. return -1;
  27. }
  28.  
  29.  
  30. public static void main(String []args)
  31. {
  32. String[] arr = { "Asterix", "Automatix", "Idefix", "Majestix", "Methusalix", "Miraculix", "Obelix", "Troubadix", "Verleihnix"};
  33. String x = "Automatix";
  34. int result = binarySearch(arr, x);
  35.  
  36. if (result == -1)
  37. System.out.println("Element nicht präsent");
  38. else
  39. System.out.println(x+ " gefunden bei "
  40. + "Index " + result);
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement