给出一个对整数数组进行排序的代码,我如何搜索和查找排序后的数组中每个元素的索引。
def countSort(arr):
output = [0 for i in range(256)]
count = [0 for i in range(256)]
result = ["" for _ in arr]
# Store count of each integers
for i in arr:
count[ord(i)] += 1
# Change count[i] so that count[i] now contains actual
# position of this integers in output array
for i in range(256):
count[i] += count[i - 1]
for i in range(len(arr)):
output[count[ord(arr[i])] - 1] = arr[i]
count[ord(arr[i])] -= 1
for i in range(len(arr)):
result[i] = output[i]
return result
驱动程序代码
arr = input("Enter numbers: ")
result = countSort(arr)
print("Sorted array is %s" % ("".join(result)))
这是我尝试做的,但是有错误
print(input("Search for Element:"))
for k in result:
if k not in result:
print("Element not found", k)
else:
print("Index of Element is ", result.index(k))
答案 0 :(得分:0)
以下是允许用户插入数字以进行搜索的代码。
如果可以在排序列表中找到代码,则代码将返回数字的索引。
注意:以下代码使用python内置排序功能,没有使用您的排序代码。
NUMBERS = [4, 6, 2, 12, 56, 34, 90]
sorted_numbers = sorted(NUMBERS)
number_to_search = input("Search for Element:")
try:
idx = sorted_numbers.index(number_to_search)
print('The index of {} is {}.'.format(number_to_search, idx))
except ValueError:
print('Cant find the number {}.'.format(number_to_search))