Must-haves in the programming world: key algorithms that are indispensable for programmers

I. Introduction

In the ocean of programming, algorithms are the soul of programmers. They not only guide the direction of the code, but also solve problems and improve efficiency. Although there are a variety of algorithms, there are some that every programmer must encounter and should master deeply. This article will take you into the world of these crucial algorithms and find out!

Two: Introduction to Common Algorithms

1. Sorting algorithm

Sorting algorithms are powerful tools for data sorting, they can sort chaotic data into order. Quick sort, merge sort, insertion sort, and selection sort are common sorting algorithms. The following is the Java sample code for each sort:

// 快速排序
public void quickSort(int[] arr, int low, int high) {
    
    
    if (low < high) {
    
    
        int pivotIndex = partition(arr, low, high); // 分区操作,找到基准元素的正确位置
        quickSort(arr, low, pivotIndex - 1); // 对基准元素左边的子数组进行递归排序
        quickSort(arr, pivotIndex + 1, high); // 对基准元素右边的子数组进行递归排序
    }
}

private int partition(int[] arr, int low, int high) {
    
    
    int pivot = arr[high]; // 选择数组的最后一个元素作为基准元素
    int i = low - 1; // i 指向比基准元素小的元素的最后位置
    for (int j = low; j < high; j++) {
    
    
        if (arr[j] < pivot) {
    
    
            i++;
            swap(arr, i, j); // 交换元素,将比基准元素小的元素放在左侧
        }
    }
    swap(arr, i + 1, high); // 将基准元素放到正确的位置上
    return i + 1; // 返回基准元素的索引
}

// 归并排序
public void mergeSort(int[] arr, int left, int right) {
    
    
    if (left < right) {
    
    
        int mid = left + (right - left) / 2;
        mergeSort(arr, left, mid); // 递归排序左半部分
        mergeSort(arr, mid + 1, right); // 递归排序右半部分
        merge(arr, left, mid, right); // 合并两个有序子数组
    }
}

// 合并两个有序子数组的操作
private void merge(int[] arr, int left, int mid, int right) {
    
    
    int n1 = mid - left + 1;
    int n2 = right - mid;
    int[] leftArr = new int[n1];
    int[] rightArr = new int[n2];

    for (int i = 0; i < n1; i++) {
    
    
        leftArr[i] = arr[left + i];
    }
    for (int j = 0; j < n2; j++) {
    
    
        rightArr[j] = arr[mid + 1 + j];
    }

    int i = 0, j = 0, k = left;
    while (i < n1 && j < n2) {
    
    
        if (leftArr[i] <= rightArr[j]) {
    
    
            arr[k++] = leftArr[i++];
        } else {
    
    
            arr[k++] = rightArr[j++];
        }
    }

    while (i < n1) {
    
    
        arr[k++] = leftArr[i++];
    }
    while (j < n2) {
    
    
        arr[k++] = rightArr[j++];
    }
}

// 插入排序
public void insertionSort(int[] arr) {
    
    
    int n = arr.length;
    for (int i = 1; i < n; i++) {
    
    
        int key = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j] > key) {
    
    
            arr[j + 1] = arr[j]; // 移动大于当前元素的元素
            j--;
        }
        arr[j + 1] = key; // 插入当前元素到正确位置
    }
}

// 选择排序
public void selectionSort(int[] arr) {
    
    
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
    
    
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
    
    
            if (arr[j] < arr[minIndex]) {
    
    
                minIndex = j; // 找到最小元素的索引
            }
        }
        swap(arr, i, minIndex); // 将最小元素放到当前位置
    }
}

// 交换数组中两个元素的位置
private void swap(int[] arr, int i, int j) {
    
    
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

2. Search algorithm

Finding algorithms are used to find specific elements in a dataset. Binary search is a common efficient algorithm, the following is its Java sample code:

// 二分查找算法
public int binarySearch(int[] arr, int target) {
    
    
    int low = 0; // 左边界
    int high = arr.length - 1; // 右边界
    while (low <= high) {
    
    
        int mid = low + (high - low) / 2; // 计算中间元素的索引
        if (arr[mid] == target) {
    
    
            return mid; // 找到目标元素,返回索引
        } else if (arr[mid] < target) {
    
    
            low = mid + 1; // 目标在右侧,调整左边界
        } else {
    
    
            high = mid - 1; // 目标在左侧,调整右边界
        }
    }
    return -1; // 目标元素未找到
}

3. Graph theory algorithm

Graph Theoretic algorithms deal with graph structures such as social networks and maps. Breadth-first search (BFS) and depth-first search (DFS) are the basic algorithms. The following is the Java sample code of DFS:

import java.util.*;

public class Graph {
    
    
    private Map<Integer, List<Integer>> graph = new HashMap<>();

    public void addEdge(int vertex, int neighbor) {
    
    
        graph.putIfAbsent(vertex, new ArrayList<>());
        graph.get(vertex).add(neighbor);
    }

    // 深度优先搜索算法
    public void dfs(int start) {
    
    
        boolean[] visited = new boolean[graph.size()];
        dfsUtil(start, visited);
    }

    private void dfsUtil(int vertex, boolean[] visited) {
    
    
        visited[vertex] = true; // 标记当前顶点为已访问
        System.out.print(vertex + " ");

        for (int neighbor : graph.getOrDefault(vertex, Collections.emptyList())) {
    
    
            if (!visited[neighbor]) {
    
    
                dfsUtil(neighbor, visited); // 递归访问未访问的邻居顶点
            }
        }
    }

    public static void main(String[] args) {
    
    
        Graph graph = new Graph();
        graph.addEdge(0, 1);
        graph.addEdge(0, 2);
        graph.addEdge(1, 2);
        graph.addEdge(2, 0);
        graph.addEdge(2, 3);
        graph.addEdge(3, 3);

        System.out.println("深度优先遍历结果:");
        graph.dfs(2); // 从顶点2开始深度优先遍历
    }
}

insert image description here

4. String arithmetic

String algorithms work with text data, such as searching, matching, and replacing. The KMP algorithm is an efficient string matching algorithm. The following is its Java sample code:

public class KMPAlgorithm {
    
    
    // KMP算法
    public void kmpSearch(String text, String pattern) {
    
    
        int m = text.length();
        int n = pattern.length();
        int[] lps = new int[n]; // 长度为n的部分匹配表

        computeLPSArray(pattern, lps); // 构建部分匹配表

        int i = 0, j = 0;
        while (i < m) {
    
    
            if (pattern.charAt(j) == text.charAt(i)) {
    
    
                i++;
                j++;
            }
            if (j == n) {
    
    
                System.out.println("Pattern found at index " + (i - j));
                j = lps[j - 1];
            } else if (i < m && pattern.charAt(j) != text.charAt(i)) {
    
    
                if (j != 0) {
    
    
                    j = lps[j - 1];
                } else {
    
    
                    i++;
                }
            }
        }
    }

    private void computeLPSArray(String pattern, int[] lps) {
    
    
        int length = 0; // 用于记录最长公共前后缀的长度
        int i = 1;
        lps[0] = 0; // 首位不可能存在公共前后缀
        while (i < pattern.length()) {
    
    
            if (pattern.charAt(i) == pattern.charAt(length)) {
    
    
                length++;
                lps[i] = length;
                i++;
            } else {
    
    
                if (length != 0) {
    
    
                    length = lps[length - 1]; // 回退到前一个公共前后缀的长度
                } else {
    
    
                    lps[i] = 0;
                    i++;
                }
            }
        }
    }

    public static void main(String[] args) {
    
    
        KMPAlgorithm kmp = new KMPAlgorithm();
        String text = "ABABDABACDABABCABAB";
        String pattern = "ABABCABAB";
        System.out.println("KMP 算法结果:");
        kmp.kmpSearch(text, pattern);
    }
}

insert image description here

Three: Summary of Key Algorithms

Mastering these core algorithms is an inevitable choice for every programmer. Not only are they widely used in computing, but they also develop abstract thinking and problem-solving skills. Through study and practice, you can demonstrate excellent skills in the field of programming.

Whether it's sorting, searching, graph theory, or string algorithms, they are your right-hand man on your programming journey. Face the challenge bravely, skillfully integrate these algorithms into your toolbox, and become an explorer and creator in the programming world!

Guess you like

Origin blog.csdn.net/Da_zhenzai/article/details/132622376