二进制搜索未排序的列表

时间:2015-11-14 21:34:49

标签: python binary-search

我需要在数字列表上使用二进制搜索,并让它返回数字的索引。列表未排序时如何执行此操作?我需要返回未排序列表的索引,而不是排序列表。

3 个答案:

答案 0 :(得分:1)

如果您希望未排序列表中的索引以及 使用二进制搜索,请尝试以下步骤:

  1. 为未排序列表中的每个项目分配索引
  2. 对列表进行排序
  3. 运行二进制搜索
  4. 返回与找到的项目相关联的索引
  5. 二进制搜索仅适用于排序列表,因此如果您需要使用该搜索算法,则无法在流程中的某处对其进行排序。

答案 1 :(得分:0)

我认为这不是很有效的方法。我的实施就在这里。

class Node(object):
   def __init__(self, index, value):
     self.index = index
     self.value = value


def binary_search(numbers, item):
    if len(numbers) == 0:
       return False
    else:
       middle = len(numbers) // 2
       if numbers[middle].value == item:
          return numbers[middle].index
       else:
          if item < numbers[middle].value:
             return binary_search(numbers[:middle], item)
          else:
             return binary_search(numbers[middle + 1:], item)

  unsorted_elems = [12, 2, 1, 5, 3, 7, 9]
  elems = []

  i = 0
  for elem in unsorted_elems:
     elems.append(Node(i, elem))
     i += 1

  elems = sorted(elems, key=lambda x: x.value)

  print(binary_search(elems, 1000)) //False
  print(binary_search(elems, 2)) // 1

答案 2 :(得分:0)

您需要对列表的副本进行排序,并将索引列表维护回原始列表。

执行此操作的一种方法是使用decorate-sort-undecorate idiom

application-context.xml

然后,您可以对已排序的值进行二进制搜索,并将索引的映射返回到原始值。

您可以使用bisect模块implement binary search

>>> values = [5, 2, 7]
>>> decorated = list(zip(value, range(len(values))))
>>> sorted_decorated = sorted(decorated)
>>> sorted_values, indices = list(zip(sorted_decorated))

>>> sorted_values
[2, 5, 7]

>>> indices
[1, 0, 2]

使用它:

def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

所以原始索引是:

>>> index(sorted_values, 5)
1