From ed996705db4128a65389ff852ac0ff8f67ac3466 Mon Sep 17 00:00:00 2001 From: Kshitij Date: Sun, 10 Dec 2023 10:37:50 +0530 Subject: [PATCH] fixed binary and fibonacci --- assignment-11.py | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/assignment-11.py b/assignment-11.py index b3940db..3d24255 100644 --- a/assignment-11.py +++ b/assignment-11.py @@ -1,10 +1,6 @@ -# BINARY AND FIBONACCI SEARCH DON'T EXACTLY WORK. -# HELP US IF YOU CAN BY CREATING AN ISSUE. - # List to store roll numbers of students that attended the program programRoll=[] attendees=int(input("Enter the number of students attending the program:\t")) -begin=0 # Function to take input for roll numbers in list def attendInput(): @@ -32,6 +28,25 @@ def sentinelSearch(roll_list, roll_search, n): else: return -1 +def binarySearch(arr, target): + arr.sort() + # Binary search on the sorted list + low, high = 0, len(arr) - 1 + while low <= high: + mid = (low + high) // 2 + mid_element = arr[mid] + + if mid_element == target: + return mid # Target element found, return its index + elif mid_element < target: + low = mid + 1 # Target is in the right half + else: + high = mid - 1 # Target is in the left half + + return -1 # Target element not found in the list + +''' +# DOESN'T WORK THIS ONE # Binary search def binarySearch(roll_list, roll_search, begin, n): if begin>n: @@ -43,9 +58,11 @@ def binarySearch(roll_list, roll_search, begin, n): return binarySearch(roll_list, roll_search, begin, mid-1) else: return binarySearch(roll_list,roll_search,mid+1,n) +''' # Fibonacci search def fibonacciSearch(students_attend, search_element, n): + students_attend.sort() fibMMm2 = 0 fibMMm1 = 1 fibM = fibMMm2 + fibMMm1 @@ -101,19 +118,19 @@ def main(): else: print(f"\nRoll number {searchAttendee} has either not been added to the list or was absent.\n") elif (optn==3): - result=binarySearch(programRoll, searchAttendee, begin, attendees) + result=binarySearch(programRoll, searchAttendee) if (result==-1): - print(f"\nRoll number {searchAttendee} attended the program.\n") - else: print(f"\nRoll number {searchAttendee} has either not been added to the list or was absent.\n") + else: + print(f"\nRoll number {searchAttendee} attended the program.\n") elif (optn==4): result=fibonacciSearch(programRoll, searchAttendee, attendees) if (result==-1): - print(f"\nRoll number {searchAttendee} attended the program.\n") - else: print(f"\nRoll number {searchAttendee} has either not been added to the list or was absent.\n") + else: + print(f"\nRoll number {searchAttendee} attended the program.\n") elif (optn==5): - print("## DESIGNED AND ENGINEERED BY KSHITIJ\n## END OF CODE") + print("\n## END OF CODE\n\n") quit() else: print("\nPlease choose a valid option (1-5)\n")