ads1_2021/code/golang/pkg/algorithms/search/binary/binary.go

55 lines
1.6 KiB
Go
Raw Normal View History

package binary
/* ---------------------------------------------------------------- *
* IMPORTS
* ---------------------------------------------------------------- */
import (
"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.Debug("x nicht in L.")
return -1
}
metrics.AddTimeCost()
m := int(len(L) / 2)
if L[m] == x {
logging.Debug("Suche in %v .. %v; m = %v; L[m] = x ==> Element gefunden.", 0, len(L)-1, m)
return m
} else if len(L) == 1 {
logging.Debug("L enthält 1 Element; L[m] =/= x; ==> x nicht in L.")
return -1
} else if x < L[m] {
logging.Debug("Suche in %v .. %v; m = %v; L[m] = %v > x ==> Suche in linker Hälfte fortsetzen.", 0, len(L)-1, m, L[m])
index := BinarySearch(L[:m], x)
return index
} else { // } else if x > L[m] {
logging.Debug("Suche in %v .. %v; m = %v; L[m] = %v < x ==> Suche in rechter Hälfte fortsetzen.", 0, len(L)-1, m, L[m])
index := BinarySearch(L[m+1:], x)
if index == -1 {
return -1 // wenn nicht gefunden
}
return index + (m + 1) // NOTE: muss Indexwert kompensieren
}
}