我设计了一种新的排序算法,名为Oracle排序,我认为它远远优于目前已知的所有排序算法(在某些假设下)。它利用甲骨文在输入序列的长度和输入序列中不同元素的数目方面实现恒定的时间复杂度。
然而,目前的计算似乎还没有准备好这样一种先进的算法,因此必须作出某些妥协,必须改变算法。由于这些修改,所提供的算法的性能大大降低。因此,我要求就如何提高算法的时间复杂度提出任何建议。
下面给出了Python 3中算法的一个示例实现。
from itertools import count, product
def oraclesort(input_seq):
"""
Find a sequence (via enumeration), with is equal the sorted input sequence.
Under ideal circumstances the enumeration would be done in parallel for all
sequences of length up to at least the length of the input, and enumerating
each of these sequences would take constant time. However, currently we are
not able to achieve such results, so we have to resort to a less efficient
sequential enumeration.
The equality of enumerated candidate sequence and the sorted input sequence
is determined by an oracle (the oracle_equals_sorted() function), which can
tell in (assumed) constant time, whether the given candidate is equal to the
sorted input. This, combined with the constant time needed to generate the
candidates, gives us a total time complexity of O(1); the best known time
complexity of an arbitrary-input sorting algorithm.
"""
for i in count():
for candidate_seq in product(input_seq, repeat=i):
if oracle_equals_sorted(candidate_seq, input_seq):
return candidate_seq
def oracle_equals_sorted(candidate_seq, input_seq):
"""
Oracle which checks whether candidate_seq equals the sorted input_seq.
The oracle should work in constant time (or ideally, in no-time), but we are
limited to deterministic Turing Machines, and therefore, we are limited
to certain implementations of the oracle, and these implementations happen
to have non-optimal (eg. nonzero) time complexity.
Despite being suboptimal, this implementation of the oracle is very elegant
in that it internally uses the oracle sort to determine whether the given
candidate sequence is equal to the sorted input sequence, hence completing
a beautiful cycle of mutual recursion.
"""
candidate_lst = list(candidate_seq)
input_lst = list(input_seq)
if not candidate_lst and not input_lst:
return True
if not candidate_lst or not input_lst:
return False
_, min_idx = min((val, idx) for idx, val in enumerate(input_lst))
input_lst_without_min = input_lst[:min_idx] + input_lst[min_idx+1:]
return candidate_lst[0] == input_lst[min_idx] and \
candidate_lst[1:] == list(oraclesort(input_lst_without_min))
发布于 2020-02-16 06:50:52
sequential_deterministic_stand_in_for_seeing_the_required_result()
和sequential_deterministic_stand_in_for_checking_the_result()
作为一个额外的因素,这从“oracle函数”的文档字符串中删除了实现细节。oraclesort()
中的嵌套循环似乎迭代了来自input_seq
的所有元素的排列--正如docstring.中所示,使用itertools.permutations()更容易阅读,并且应该测试相同长度的序列,only. (比相关的bogobogosort更快,因为没有重复检查相同的序列)。input_lst_without_min
不同,您可以只使用确定最小值,将其与候选序列的开头进行比较,并从序列中删除它以递归排序: input_lst_without_min = input_seq[:]
input_lst_without_min.remove(min(input_seq))
https://codereview.stackexchange.com/questions/237351
复制相似问题