Search code examples
pythonsortedlist

How to search a specific data in sorted list or given data?


def BinarySearch(data_of_xyz, search_key):
    low_indx = 0
    hig_indx = len(data_of_xyz) -1
    found = False
    while low_indx<=hig_indx and not found:
        mid_indx = (low_indx + hig_indx) // 2
        if search_key == data_of_xyz[mid_indx]:
            found = True
        elif search_key > data_of_xyz[mid_indx]:
            low_indx = mid_indx + 1
        else:
            hig_indx = mid_indx - 1
    if found == True:
        print("Your search key is at position: ")
    else:
        print("Your key is not found: ")

data_of_xyz = [13, 24, 32, 35, 78]
data_of_xyz.sort()
print(data_of_xyz)
search_key = int(input("Enter the required key: "))
BinarySearch(data_of_xyz,search_key)

OUTPUT

Enter the required key: 35
Your search key is at position: 

if you see it doesn't show 35 position from the list!


Solution

  • It didn't print the value because you told it to print only the header text, not the value.

    if found:
        print("Your search key is at position: ", mid_indx)
    

    fixes the problem:

    [13, 24, 32, 35, 78]
    Enter the required key: 35
    Your search key is at position:  3