2021-10-23 13:20:37 +02:00
|
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
# IMPORTS
|
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
from local.maths import *;
|
|
|
|
|
from local.typing import *;
|
|
|
|
|
|
|
|
|
|
from code.core.log import *;
|
2021-10-24 12:28:37 +02:00
|
|
|
|
from code.algorithms.methods import *;
|
2021-10-23 13:20:37 +02:00
|
|
|
|
|
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
# GLOBAL VARIABLES/CONSTANTS
|
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
#
|
|
|
|
|
|
2021-10-24 12:28:37 +02:00
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
# 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;
|
|
|
|
|
|
2021-10-23 13:20:37 +02:00
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
# ALGORITHM binary search
|
|
|
|
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
2021-10-24 12:28:37 +02:00
|
|
|
|
@algorithmInfos(name='Binärsuchalgorithmus', outputnames='index', checks=True, metrics=True, preChecks=preChecks, postChecks=postChecks)
|
2021-10-23 13:20:37 +02:00
|
|
|
|
def BinarySearch(L: List[int], x: int) -> int:
|
|
|
|
|
'''
|
|
|
|
|
Inputs: L = Liste von Zahlen, x = Zahl.
|
2021-10-24 13:18:39 +02:00
|
|
|
|
|
2021-10-23 13:20:37 +02:00
|
|
|
|
Annahme: L sei aufsteigend sortiert.
|
2021-10-24 13:18:39 +02:00
|
|
|
|
|
2021-10-23 13:20:37 +02:00
|
|
|
|
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));
|
2021-10-24 12:28:37 +02:00
|
|
|
|
index = BinarySearch(L=L[:m], x=x);
|
2021-10-23 13:20:37 +02:00
|
|
|
|
return index;
|
|
|
|
|
else: # x > L[m]
|
|
|
|
|
logDebug('Suche in L[m+1], L[m+2], ..., L[len(L)-1] fortsetzen, m = {}.'.format(m));
|
2021-10-24 12:28:37 +02:00
|
|
|
|
index = BinarySearch(L=L[m+1:], x=x);
|
2021-10-25 11:27:33 +02:00
|
|
|
|
if index >= 0:
|
|
|
|
|
index += (m + 1); # NOTE: muss Indexwert kompensieren
|
|
|
|
|
return index;
|