Binary search only works if the input list is sorted. Currently, our lists are not sorted.
In main, after printing the list of cities, add another line of code to sort the list:
city_list.sort() # use the name of your list in place of city_list
Then print the sorted version of the list.
Sample input and output:
Name of input file: cities-small.txt The original list of cities is: 0: Santa Rosa 1: Petaluma 2: Rohnert Park 3: Windsor 4: Healdsburg After sorting, the new list is: 0: Healdsburg 1: Petaluma 2: Rohnert Park 3: Santa Rosa 4: Windsor Enter the name of a city: Petaluma The position of Petaluma is: Linear search: 1 Enter the name of a city: Windsor The position of Windsor is: Linear search: 4 Enter the name of a city: Cotati The position of Cotati is: Linear search: None Enter the name of a city: quit
def binary_search(search_list, value_to_find): """ Uses a binary search function to find the position of an item in a list Parameters: the list; the item to search for Returns: the position of the item in the list (or None if it is not in the list) """ pass
Name of input file: cities-small.txt The original list of cities is: 0: Santa Rosa 1: Petaluma 2: Rohnert Park 3: Windsor 4: Healdsburg After sorting, the new list is: 0: Healdsburg 1: Petaluma 2: Rohnert Park 3: Santa Rosa 4: Windsor Enter the name of a city: Petaluma The position of Petaluma is: Linear search: 1 Binary search: None Enter the name of a city: Windsor The position of Windsor is: Linear search: 4 Binary search: None Enter the name of a city: Cotati The position of Cotati is: Linear search: None Binary search: None Enter the name of a city: quit
Name of input file: cities-small.txt The original list of cities is: 0: Santa Rosa 1: Petaluma 2: Rohnert Park 3: Windsor 4: Healdsburg After sorting, the new list is: 0: Healdsburg 1: Petaluma 2: Rohnert Park 3: Santa Rosa 4: Windsor Enter the name of a city: Windsor Linear search: 4 **Binary search iterations: 3 Binary search: 4 Enter the name of a city: Rohnert Park Linear search: 2 **Binary search iterations: 1 Binary search: 2 Enter the name of a city: SSU Linear search: None **Binary search iterations: 2 Binary search: None Enter the name of a city: quit