60 lines
2.0 KiB
Python
60 lines
2.0 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
# IMPORTS
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
|
||
from local.maths import *;
|
||
from local.typing import *;
|
||
|
||
from code.core.log import *;
|
||
from code.algorithms.methods import *;
|
||
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
# GLOBAL VARIABLES/CONSTANTS
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
|
||
#
|
||
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
# CHECKS
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
|
||
def preChecks(L: List[int], **_):
|
||
assert L == sorted(L), 'Ungültiger Input: L muss aufsteigend sortiert sein!';
|
||
return;
|
||
|
||
def postChecks(L: List[int], x: int, index: int, **_):
|
||
value = L[index] if index >= 0 else None;
|
||
assert value == x, 'Der Algorithmus hat versagt.';
|
||
return;
|
||
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
# ALGORITHM binary search
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
|
||
@algorithmInfos(name='Binärsuchalgorithmus', outputnames='index', checks=True, metrics=True, preChecks=preChecks, postChecks=postChecks)
|
||
def BinarySearch(L: List[int], x: int) -> int:
|
||
'''
|
||
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.
|
||
'''
|
||
if len(L) == 0:
|
||
logDebug('x nicht in L');
|
||
return -1;
|
||
AddToCounter();
|
||
m = math.floor(len(L)/2);
|
||
if L[m] == x:
|
||
logDebug('x in Position m gefunden');
|
||
return m;
|
||
elif x < L[m]:
|
||
logDebug('Suche in L[0], L[1], ..., L[m] fortsetzen, m = {}.'.format(m));
|
||
index = BinarySearch(L=L[:m], x=x);
|
||
return index;
|
||
else: # x > L[m]
|
||
logDebug('Suche in L[m+1], L[m+2], ..., L[len(L)-1] fortsetzen, m = {}.'.format(m));
|
||
index = BinarySearch(L=L[m+1:], x=x);
|
||
return (m + 1) + index; # NOTE: muss Indexwert kompensieren
|