问题:您需要在已排序的集合中查找特定元素,但您想要一种能减少比较次数的高效算法,尤其是对于较大的数据集。

解决方案: 使用跳转搜索算法,也称为块搜索。

代码示例:

import math

def jump_search (arr, target):
  n = len (arr)
  block_size = int (math.sqrt (n)) # Determine the block size

  # Step 1: Jump to the beginning of the first block
  left, right = 0, 0
  while right < n and arr[right] < target:
    left = right
    right += block_size
    right = min(right, n - 1) # Ensure the right boundary does not exceed the list length

    # Step 2: Perform a linear search within the current block
    for i in range(left, right + 1):
      if arr[i] == target:
        return i # Element found
    return -1 # Element not found

# Example usage:
sorted_list = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
target_element = 13

result = jump_search (sorted_list, target_element)

if result != -1:
  print(f"Element {target_element} found at index {result}")
else:
  print(f"Element {target_element} not found in the list")

跳转搜索(块搜索)算法