Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

My binary search is not working. When I search for a name that actually is in the list, it says not found! Please help, I

My binary search is not working. When I search for a name that actually is in the list, it says not found! Please help, I know something small needs to be added or changed and I cant figure it out. This is python

with open('first_names.csv','r') as file: #reading all lines into a variable data=file.readlines() #stripping new line character data=[i.strip(' ') for i in data] #list to store data names = [] #iterating over the data for i in data: #adding each namesinto list names.append(i) #print('Unsorted list: ',names) #GeeksforGeeks Algorithm def mergeSort(arr): if len(arr) > 1: # Finding the mid of the array mid = len(arr)//2 # Dividing the array elements L = arr[:mid] # into 2 halves R = arr[mid:] # Sorting the first half mergeSort(L) # Sorting the second half mergeSort(R) i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 #GeeksforGeeks Algorithm def binarySearch (arr, l, r, x): # Check base case if r >= l: mid = l + (r - l) // 2 # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it # can only be present in left subarray elif arr[mid] > x: return binarySearch(arr, l, mid-1, x) # Else the element can only be present # in right subarray else: return binarySearch(arr, mid + 1, r, x) else: # Element is not present in the array return -1 mergeSort(names) #sorting list search = input("Search for a name: ")

# Function call result = binarySearch(names, 0, len(names)-1, search) if result != -1: print ("Element is present at index ",result) else: print ("Element is not present in array")

#getting length of all names adding them together lenNames = 0 for i in names: if len(i) > 1: lenNames = lenNames + len(i) int_lenNames = int(lenNames)

#getting average of length of names avgLen = int_lenNames//len(names) print("The average length of these first names is: ",avgLen)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Driven Web Sites

Authors: Joline Morrison, Mike Morrison

2nd Edition

? 061906448X, 978-0619064488

More Books

Students also viewed these Databases questions