package binary /* ---------------------------------------------------------------- * * IMPORTS * ---------------------------------------------------------------- */ import ( "fmt" "ads/internal/core/logging" "ads/internal/core/metrics" ) /* ---------------------------------------------------------------- * * GLOBAL VARIABLES/CONSTANTS * ---------------------------------------------------------------- */ // /* ---------------------------------------------------------------- * * ALGORITHM binary search * ---------------------------------------------------------------- */ /* Inputs: L = Liste von Zahlen, x = Zahl. Annahme: L sei aufsteigend sortiert. Outputs: Position von x in L, sonst −1 wenn x nicht in L. */ func BinarySearch(L []int, x int) int { if len(L) == 0 { logging.LogDebug(fmt.Sprintf("x nicht in L")) return -1 } metrics.AddTimeCost() m := int(len(L) / 2) if L[m] == x { logging.LogDebug(fmt.Sprintf("x in Position m gefunden")) return m } else if x < L[m] { logging.LogDebug(fmt.Sprintf("Suche in linker Hälfte fortsetzen.")) index := BinarySearch(L[:m], x) return index } else { // } else if x > L[m] { logging.LogDebug(fmt.Sprintf("Suche in rechter Hälfte fortsetzen.")) index := BinarySearch(L[m+1:], x) if index >= 0 { index += (m + 1) // NOTE: muss Indexwert kompensieren } return index } }