Write a program using function that takes a sorted list and a number as an argument. Search for the number in the sorted list using binary search. Attach output screenshots also.

 Program:-

# Selection sort (Optional but included)
def selectionSort(array, size):
    for step in range(size):
        minindex = step #assume index as a min index value

        for i in range(step + 1, size):
            # to sort in descending order, change > to < in this line
            # select the minimum element in each loop

            if array[i] < array[minindex]:
            minindex = i

        # put min at the correct position
        (array[step], array[minindex]) = (array[minindex], array[step]) #swapping is performed

# Iterative Binary Search Function
# It returns index of x in given array arr if present,
# else returns -1

def binary_search(lst, x):
    low = 0
    high = len(lst) - 1
    mid = 0

    while low <= high:

        mid = (high + low) // 2

        # If x is greater, ignore left half

        if lst[mid] < x:
            low = mid + 1

        # If x is smaller, ignore right half
        elif lst[mid] > x:
            high = mid - 1

        # means x is present at mid
        else:
            return mid

    # If we reach here, then the element was not present
    return -1

lst = eval(input('Enter your list ')) #Take list from user
size = len(lst) #Take value from user to be search out
selectionSort(lst, size) #optional but included because sometimes the list may not be in sorted order
print('Entered list is: ')
print(lst)
x = int(input('Enter the values to be Search: '));

# Function call
result = binary_search(lst, x)

if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in list")

Program images:-





Output:-

When element is present inside a list or can array. Like here list is [ 5, 10 , 20, 30, 69 ] and 69 is present in a list.


When element is not present in a list. Like here list is [ 5, 10, 20, 30, 40] and 11 is not present in a list.


Program Explanation:-

Firstly, user will enter the list according to his/her choice. Then, python check that whether the list is sorted as i put the selection sort there, so if in case the user enter the list not in a sorted manner. Therefore, selection make the list in a ascending order. Thereby, user need to enter the element to search in a list. Then, binary search function called out which takes two parameters list and element to be search. It will check whether element or a value is present inside a list using binary search. If element is present inside a list, then return index of that element. Otherwise, return -1. Finally, if index is returned from a function, it means that element is present in a list, if -1 then, element not present which is also discussed above.


Comments