45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
# IMPORTS
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
|
||
from local.maths import *;
|
||
from local.typing import *;
|
||
|
||
from code.core.log import *;
|
||
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
# GLOBAL VARIABLES/CONSTANTS
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
|
||
#
|
||
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
# ALGORITHM binary search
|
||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
|
||
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[:m], 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[m+1:], x);
|
||
return (m + 1) + index; # NOTE: muss Indexwert kompensieren
|