【发布时间】:2015-07-12 17:42:50
【问题描述】:
我正在尝试编写一个三元搜索算法函数,该函数使用一个排序的整数列表和一个值。它类似于二分查找,只是在每次迭代中通过选取两个索引 ind1 和 ind2 (ind1
• 区域 1 包含索引值小于 ind1 的所有项目
• 区域 2 包含索引值大于 ind1 但小于 ind2 的所有项目
• 区域 3 包含索引值大于 ind2 的所有项目
如果可能,这些区域的大小应该相等。如果这不可能,那么Region 1的大小必须大于或等于Region 2的大小,Region 2的大小必须大于或等于Region 3的大小。任意两个区域的大小最多相差一个。
我试图遵循的格式是:
如果搜索区域的大小为
对 v 执行线性搜索
其他
如果 L[ind1] 等于 v,则选择索引 ind1 和 ind2
停止,我们找到了 v else if v
如果 L[ind2] 等于 v,则重复 Region 1 作为新的搜索区域
停止,我们找到了 v else if v
重复区域 2 作为新的搜索区域
重复区域 3 作为新的搜索区域
~~~~~
除了搜索列表之外,我还需要生成算法检查的步骤。
~~~~~
例如:
ternary_search([6,12,18,22,29,37,38,41,51,53,55,67,73,75,77,81,8 6,88,94], 88) 应该打印:
检查 88 是否等于 38
检查 88 是否小于 38
检查 88 是否等于 75
检查 88 是否小于 75
检查 88 是否等于 81
检查 88 是否小于 81
检查 88 是否等于 88
搜索成功
88 位于索引 17
一共做了7次比较
~~~~~ 我写的代码是:
`def ternary_search (L, key):
left = 0
right = len(L) - 1
while left <= right:
ind1 = left
ind2 = left + (right - left) // 3
ind3 = left + 2 * (right - left) // 3
n = 0
if key == L[left]:
n += 1
print("Checking if " + str(key) + " is equal to " + str(left))
print("Search successful")
print(str(key) + " is located at index " + str(left))
print("A total of " + str(n) + " comparisons were made")
return
elif key == L[right]:
n += 1
print("Checking if " + str(key) + " is equal to " + str(right))
print("Search successful")
print(str(key) + " is located at index " + str(right))
print("A total of " + str(n) + " comparisons were made")
return
elif key < L[left] or key > L[right]:
n += 1
print("Search not successful")
print("A total of " + str(n) + " comparisons were made")
return
elif key <= L[ind2]:
n += 1
print("Checking if " + str(key) + " is less than " + str(L[ind2]))
right = ind2 -1
elif key > L[ind2] and key <= L[ind3]:
n += 1
print("Checking if " + str(key) + " is less than " + str(L[ind2]))
print("Checking if " + str(key) + " is equal to " + str(L[ind3]))
print("Checking if " + str(key) + " is less than " + str(L[ind3]))
left = ind2 + 1
right = ind3
else:
n += 1
print("Checking if " + str(key) + " is less than " + str(L[ind3]))
left = ind3 + 1
return`
当我打电话时:
ternary_search([6,12,18,22,29,37,38,41,51,53,55,67,73,75,77,81,86,88,94], 51)
打印出来:
Checking if 51 is less than 38
Checking if 51 is equal to 73
Checking if 51 is less than 73
Checking if 51 is less than 51
Search not successful
A total of 1 comparisons were made
什么时候应该打印:
Checking if 51 is equal to 38
Checking if 51 is less than 38
Checking if 51 is equal to 75
Checking if 51 is less than 75
Checking if 51 is equal to 53
Checking if 51 is less than 53
Checking if 51 is equal to 41
Checking if 51 is equal to 51
Search successful
51 is located at index 8
A total of 8 comparisons were made
【问题讨论】:
标签: python algorithm search time-complexity ternary-search-tree