What are your feelings

  • Happy
  • Normal
  • Sad

常见的搜索算法

常用的搜索算法:

1. 线性搜索(Linear Search)

原理:从列表的第一个元素开始逐个比较,直到找到目标值或遍历完整个列表。 Python 示例

def linear_search(arr, target):
    for index, value in enumerate(arr):
        if value == target:
            return index
    return -1

# 示例
arr = [4, 2, 5, 7, 1]
target = 5
print(linear_search(arr, target))  # 输出: 2

常见用途:小型数据集或未排序的数据集合。


2. 二分搜索(Binary Search)

原理:在有序数组中查找,通过反复折半缩小搜索范围。 Python 示例

def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

# 示例
arr = [1, 2, 3, 4, 5, 6, 7]
target = 4
print(binary_search(arr, target)) # 输出: 3

常见用途:用于查找有序数据,如排序后的列表。


3. 深度优先搜索(DFS, Depth First Search)

原理:优先探索到达的最深节点,再逐步回溯。 Python 示例

def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited

# 示例
graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': [], 'F': []}
print(dfs(graph, 'A')) # 输出: {'A', 'B', 'D', 'E', 'C', 'F'}

常见用途:图遍历、路径发现、迷宫解法。


4. 广度优先搜索(BFS, Breadth First Search)

原理:优先探索同一层的所有节点,逐层向下展开。 Python 示例

from collections import deque

def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return visited

# 示例
graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': [], 'F': []}
print(bfs(graph, 'A')) # 输出: {'A', 'B', 'C', 'D', 'E', 'F'}

常见用途:最短路径问题、层次遍历。


5. 跳表搜索(Skip List Search)

原理:通过额外的索引层加速搜索,适用于动态有序链表。 Python 示例(模拟跳表查找):

class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next

class SkipList:
def __init__(self):
self.head = Node()

def search(self, target):
current = self.head
while current:
while current.next and current.next.value <= target:
current = current.next
if current.value == target:
return True
current = current.down
return False

常见用途:有序列表的快速查找,如分布式数据库。


6. *A 算法**

原理:基于启发式的搜索算法,使用 f(n) = g(n) + h(n) 来估算节点到目标的总代价。 Python 示例

from heapq import heappop, heappush

def a_star(graph, start, goal, heuristic):
open_set = []
heappush(open_set, (0, start))
came_from = {}
g_score = {node: float('inf') for node in graph}
g_score[start] = 0

while open_set:
_, current = heappop(open_set)

if current == goal:
return g_score[goal]

for neighbor, weight in graph[current]:
tentative_g_score = g_score[current] + weight
if tentative_g_score < g_score[neighbor]:
g_score[neighbor] = tentative_g_score
f_score = tentative_g_score + heuristic(neighbor, goal)
heappush(open_set, (f_score, neighbor))
came_from[neighbor] = current
return -1

# 示例
graph = {'A': [('B', 1), ('C', 3)], 'B': [('D', 1)], 'C': [('D', 1)], 'D': []}
heuristic = lambda x, y: 1 # 简单启发函数
print(a_star(graph, 'A', 'D', heuristic)) # 输出: 2

常见用途:路径规划、导航系统。


7. 哈希查找(Hash Search)

原理:利用哈希表,通过计算键值的哈希快速定位存储位置。 Python 示例

hash_table = {'key1': 'value1', 'key2': 'value2'}
print(hash_table.get('key1')) # 输出: value1

常见用途:键值对查找,如缓存系统、数据库索引。


这些搜索算法根据使用场景的不同选择,适用于处理无序数据、有序数据、图或网格等结构。

 

索引