|
| 1 | +# File: Programs/samplebinarysearch.py |
| 2 | + |
| 3 | +import sys |
| 4 | +import os |
| 5 | +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'Lib')) |
| 6 | +import flexsearch |
| 7 | + |
| 8 | +def main(): |
| 9 | + while True: |
| 10 | + # User input |
| 11 | + numbers = input("\nEnter numbers separated by space or comma (or '-1' to quit): ").strip() |
| 12 | + if numbers.lower() == '-1': |
| 13 | + break |
| 14 | + if not numbers: |
| 15 | + print("No numbers entered. Try again.") |
| 16 | + continue |
| 17 | + |
| 18 | + mode = input("Enter sort mode (a/d/min/max): ").strip().lower() |
| 19 | + if mode not in ('a', 'd', 'min', 'max'): |
| 20 | + print("Invalid sort mode. Try again.") |
| 21 | + continue |
| 22 | + |
| 23 | + |
| 24 | + target_str = input("Enter target number for search: ").strip() |
| 25 | + try: |
| 26 | + target = int(target_str) |
| 27 | + except ValueError: |
| 28 | + print("Invalid target number. Try again.") |
| 29 | + continue |
| 30 | + |
| 31 | + # Parse numbers safely |
| 32 | + try: |
| 33 | + arr = flexsearch.parse_numbers(numbers) |
| 34 | + if not arr: |
| 35 | + print("No valid numbers found. Try again.") |
| 36 | + continue |
| 37 | + except ValueError: |
| 38 | + print("Invalid number format. Try again.") |
| 39 | + continue |
| 40 | + |
| 41 | + # Sort and search |
| 42 | + sorted_arr = flexsearch.sort_numbers(arr, mode) |
| 43 | + idx = flexsearch.binary_search(sorted_arr, target) |
| 44 | + |
| 45 | + # Output results |
| 46 | + print("\nInput string:", numbers) |
| 47 | + print("Sorted array:", sorted_arr) |
| 48 | + if idx == -1: |
| 49 | + print(f"Target {target} not found in the array.") |
| 50 | + else: |
| 51 | + print(f"Target {target} found at index:", idx) |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + main() |
0 commit comments