简体   繁体   English

查找排序数组中元素的索引

[英]Finding Index of element in sorted array

Given a code that sorts an array of integers, how do i search and find the index of each element in the sorted array.给定一个对整数数组进行排序的代码,我如何搜索并找到排序数组中每个元素的索引。

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

driver code驱动程序代码

    arr = input("Enter numbers: ")
    result = countSort(arr)
    print("Sorted array is %s" % ("".join(result)))

This is what i tried to do but it has errors这是我试图做的,但它有错误

      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))

Below is a code that let the user insert a number to search.下面是让用户插入一个数字进行搜索的代码。

The code return the index of the number if it can be found in the sorted list.如果可以在排序列表中找到该数字,则该代码返回该数字的索引。

Note : The code below uses python builtin sort and does not make use of your sorting code.注意:下面的代码使用 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)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM