java.util.Arrays.binarySearch als Multitool

Thomas Darimont

Erfahrenes Mitglied
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

Java:
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:
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
 
Zurück