Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class stringSearch {
- static int binarySearch(String[] arr, String x)
- {
- int l = 0, r = arr.length - 1;
- while (l <= r) {
- int m = l + (r - l) / 2;
- int res = x.compareTo(arr[m]);
- // prüfen ob x in der Mitte
- if (res == 0)
- return m;
- // If x größer, linke Hälfte ignorieren
- if (res > 0)
- l = m + 1;
- // If x ist kleiner, rechte Hälfte ignorieren
- else
- r = m - 1;
- }
- return -1;
- }
- public static void main(String []args)
- {
- String[] arr = { "Asterix", "Automatix", "Idefix", "Majestix", "Methusalix", "Miraculix", "Obelix", "Troubadix", "Verleihnix"};
- String x = "Automatix";
- int result = binarySearch(arr, x);
- if (result == -1)
- System.out.println("Element nicht präsent");
- else
- System.out.println(x+ " gefunden bei "
- + "Index " + result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement