You must know the algorithms (including codes) that programmers must master


insert image description here

As a programmer, mastering some basic algorithms is very important for solving problems and optimizing code. Here are some basic algorithms that programmers should know, with sample code:

1. Sorting algorithm:

  • Bubble Sort: sort by comparing and exchanging adjacent elements.
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr

# 示例
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print(sorted_arr)  # 输出: [11, 12, 22, 25, 34, 64, 90]
  • Quick Sort: Sorts by selecting a pivot element and dividing the array into two sub-arrays.
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr)//2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

# 示例
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = quick_sort(arr)
print(sorted_arr)  # 输出: [11, 12, 22, 25, 34, 64, 90]

2. Search algorithm:

  • Binary Search: For sorted arrays, the search range is halved after each comparison to quickly locate the target element.
def binary_search(arr, target):
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

# 示例
arr = [11, 12, 22, 25, 34, 64, 90]
target = 25
index = binary_search(arr, target)
print(index)  # 输出: 3

3. Graph algorithm:

  • Breadth-First Search (BFS): Starting from the starting node, traverse the nodes of the graph layer by layer.
from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    while queue:
        node = queue.popleft()
        if node not in visited:
            visited.add(node)
            print(node)
            neighbors = graph[node]
            queue.extend(neighbors)

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

4. Dynamic programming:

  • Fibonacci Sequence: Calculate the Fibonacci sequence by defining state transition equations.
def fibonacci(n):
    if n <= 1:
        return n
    a, b = 0, 1
    for _ in range(2, n+1):
        a, b = b, a + b
    return b

# 示例
n = 10
result = fibonacci(n)
print(result)  # 输出: 55

5. String matching algorithm:

  • KMP algorithm: By preprocessing the pattern string, the information of the matched characters is used to skip unnecessary comparisons.
def build_lps(pattern):
    lps = [0] * len(pattern)
    i, j = 0, 1
    while j < len(pattern):
        if pattern[i] == pattern[j]:
            i += 1
            lps[j] = i
            j += 1
        else:
            if i != 0:
                i = lps[i-1]
            else:
                lps[j] = 0
                j += 1
    return lps

def kmp(text, pattern):
    lps = build_lps(pattern)
    i, j = 0, 0
    while i < len(text) and j < len(pattern):
        if text[i] == pattern[j]:
            i += 1
            j += 1
        else:
            if j != 0:
                j = lps[j-1]
            else:
                i += 1
    if j == len(pattern):
        return i - j
    return -1

# 示例
text = "ABABDABACDABABCABAB"
pattern = "ABABCABAB"
index = kmp(text, pattern)
print(index)  # 输出: 10

These are just a few examples of the basic algorithms a programmer needs to master, including examples of sorting, searching, graph algorithms, dynamic programming, and string matching. In fact, there are many other important algorithms, such as tree traversal, shortest path algorithm for graphs, solutions to dynamic programming problems, etc. Programmers should further study and apply more algorithms according to their needs and interests.

Guess you like

Origin blog.csdn.net/superdangbo/article/details/131597454