2025-04-11 14:09:33 +02:00

62 lines
1.6 KiB
Python

import random
from utils.memory_array import MemoryArray
from utils.memory_cell import MemoryCell
from utils.memory_manager import MemoryManager
from utils.memory_range import mrange
from utils.literal import Literal
def binary_search(z: MemoryArray, s: MemoryCell, l: Literal = None, r: Literal = None):
"""
Perform a binary search on the sorted array z for the value x.
"""
if l is None:
l = Literal(0)
if r is None:
r = Literal(z.length().pred())
if l > r:
return None
with MemoryCell(l) as m:
m += r
m //= Literal(2)
if s < z[m]:
return binary_search(z, s, l, m.pred())
elif s > z[m]:
return binary_search(z, s, m.succ(), r)
else:
return m
def analyze_complexity(sizes):
"""
Analysiert die Komplexität
:param sizes: Eine Liste von Eingabegrößen für die Analyse.
"""
for size in sizes:
MemoryManager.purge() # Speicher zurücksetzen
random_array = MemoryArray.create_sorted_array(size)
search_value = random.randint(-100, 100)
binary_search(random_array, MemoryCell(search_value))
MemoryManager.save_stats(size)
MemoryManager.plot_stats(["cells", "compares", "adds"])
if __name__ == "__main__":
# Example usage
arr = MemoryArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
search_value = MemoryCell(8)
result = binary_search(arr, search_value)
if result is not None:
print(f"Value {search_value} found at index {result}.")
else:
print(f"Value {search_value} not found in the array.")
sizes = range(1, 1001, 2)
analyze_complexity(sizes)