如何在排序列表或给定数据中搜索特定数据?
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)
输出
Enter the required key: 35
Your search key is at position:
如果您看到它没有显示列表中的第 35 个位置!
它没有打印值,因为你告诉它只打印 header 文本,而不是值。
if found:
print("Your search key is at position: ", mid_indx)
修复了问题:
[13, 24, 32, 35, 78]
Enter the required key: 35
Your search key is at position: 3
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)
输出
Enter the required key: 35
Your search key is at position:
如果您看到它没有显示列表中的第 35 个位置!
它没有打印值,因为你告诉它只打印 header 文本,而不是值。
if found:
print("Your search key is at position: ", mid_indx)
修复了问题:
[13, 24, 32, 35, 78]
Enter the required key: 35
Your search key is at position: 3