52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
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("x in Position m gefunden")
|
||
return m
|
||
} else if x < L[m] {
|
||
logging.Debug("Suche in linker Hälfte fortsetzen.")
|
||
index := BinarySearch(L[:m], x)
|
||
return index
|
||
} else { // } else if x > L[m] {
|
||
logging.Debug("Suche in rechter Hälfte fortsetzen.")
|
||
index := BinarySearch(L[m+1:], x)
|
||
if index >= 0 {
|
||
index += (m + 1) // NOTE: muss Indexwert kompensieren
|
||
}
|
||
return index
|
||
}
|
||
}
|