Hallo,

hier mal ein kleines Beispiel dazu was man alles mit der Methode binarySearch von j.u.Arrays machen kann:

- Ein Wert in einem Array suchen (wenn Wert enthalten bekommt man den Index des Wertes zurück)
- Den Einfügeindex eines Wertes finden (wenn der Wert noch nicht enthalten ist bekommen wir den neuen Einfügeindex als negative Zahl
- Den nächst größeren Wert zu einem gegebenen Wert der nicht im Array enthalten ist
finden der noch im Array enthalten ist

Code java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package de.tutorials;
 
import java.util.Arrays;
 
public class BinarySearchAsMultitool {
 
  public static void main(String[] args) {
    double[] values = { 1, 2, 5, 5.59, 8.89 };
 
    System.out.println("values: "+ Arrays.toString(values));
    
    demoBinarySearch(values, 8.87);
    demoBinarySearch(values, 4.95);
    demoBinarySearch(values, 2);
  }
 
 
  protected static void demoBinarySearch(double[] values, double value) {
    try {
      System.out.println("#########");
      System.out.println("Demo: " + value);
      System.out.println(contains(values, value));
      if (!contains(values, value)) {
        System.out.println(newInsertionIndex(values, value));
      }
      System.out.println(getNextFollowingMatch(values, value));
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
    }
  }
 
 
  private static double getNextFollowingMatch(double[] values, double value) {
    System.out.print("getNextFollowingMatch in values ->");
    int index = Arrays.binarySearch(values, value);
    if (index < 0) {
      index = Math.abs(index);
      index -= 1;
    }
 
    if (index >= values.length) {
      throw new RuntimeException("value " + value + " not contained in values: " + Arrays.toString(values));
    }
 
    return values[index];
  }
 
 
  private static int newInsertionIndex(double[] values, double value) {
    System.out.print("newInsertionIndex in values ->");
    return Math.abs(Arrays.binarySearch(values, value)) - 1;
  }
 
 
  private static boolean contains(double[] values, double value) {
    System.out.print("contained in values ->");
    return Arrays.binarySearch(values, value) >= 0;
  }
 
}

Ausgabe:
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
values: [1.0, 2.0, 5.0, 5.59, 8.89]
#########
Demo: 8.87
contained in values ->false
contained in values ->newInsertionIndex in values ->4
getNextFollowingMatch in values ->8.89
#########
Demo: 4.95
contained in values ->false
contained in values ->newInsertionIndex in values ->2
getNextFollowingMatch in values ->5.0
#########
Demo: 2.0
contained in values ->true
contained in values ->getNextFollowingMatch in values ->2.0

Gruß Tom