有一个分配,我必须对名称列表进行排序,然后显示它。然后让用户输入其中一个名称并搜索数组并在数组中显示有序数字。我几乎完成了所有工作,但我无法让这部分工作。
如果我输入其中一个名称,它只会返回相同的名称,但不会在索引中提供有序的数字。如何更改代码,以便正确显示输入程序的名称编号?
def main():
SIZE = 10
names = ['Ross Harrison', 'Hannah Beauregard', 'Bob White', 'Ava Fisher', 'Chris Rich', 'Xavier Adams', 'Sasha Ricci', 'Danielle Porter', 'Gordon Pike', 'Matt Hoyle']
searchName = str()
index = int()
selectionSort(names, SIZE)
print('Sorted order:')
for index in range (0, SIZE):
print(names[index])
searchName = input('Enter a name to search for: ')
index = binarySearch(names, searchName, SIZE)
if index != -1:
print('The ordered number of this name is ' + str(names[index]))
else:
print(searchName + 'was not found.')
def selectionSort(array, arraySize):
startScan = int(); minIndex = int(); minValue = int(); index = int()
for startScan in range (0, arraySize - 1):
minIndex = startScan
minValue = array[startScan]
for index in range (startScan + 1, arraySize):
if array[index] < minValue:
minValue = array[index]
minIndex = index
array[minIndex] = array[startScan]
array[startScan] = minValue
def binarySearch(array, value, arraySize):
position = -1
first = 0
last = arraySize - 1
found = False
middle = int()
while not found and first <= last:
middle = int((first + last) / 2)
if array[middle] == value :
found = True
position = middle
elif array[middle] > value:
last = middle - 1
else:
first = middle + 1
return position
main()
答案 0 :(得分:0)
我认为你有一个简单的,一线的变化。 你得到的是名字而不是索引,因为这正是你告诉它打印的内容。相反,使用这个:
print('The index of this name is ', index)
您的原件在该位置查找名称时遇到了额外的麻烦。