Java Review Notes-Common Algorithms: Search Algorithms


Algorithm overview

An algorithm is a series of explicit instructions or steps for solving a problem. It is an orderly process of identifying and solving problems through a limited and clear series of instructions. An algorithm can be described as a computational model that transforms input data into output results.

Algorithms usually consist of a number of basic operations that can be performed in a certain order to accomplish a specific task. Algorithms can be used to solve various problems such as search, sorting, graphics processing, data compression, artificial intelligence, etc.

Features of the algorithm include:

  1. Clarity: The algorithm must describe each step and operation clearly so that it can be executed correctly.
  2. Finiteness: The algorithm must stop running within a limited time and cannot loop indefinitely or execute indefinitely.
  3. Inputs: An algorithm has zero or more inputs, which are data or information used to execute the algorithm.
  4. Output: An algorithm produces one or more outputs, which are the result of processing input data by the algorithm.
  5. Determinism: Given the same input conditions, the execution steps and results of the algorithm should be the same.
  6. Feasibility: The algorithm should be feasible, i.e. it can be practically applied and completed within a reasonable time.

By designing and implementing efficient and correct algorithms, the efficiency and accuracy of problem solving can be improved. Algorithms are one of the core foundations of computer science and programming.

1. Basic search/linear search

(1) Introduction to algorithm

The linear search algorithm, also known as the sequential search algorithm, is a basic search algorithm suitable for unordered data sets. The basic idea is to compare one by one starting from the first element of the data set until the target element is found or the entire data set is traversed.

The time complexity of the linear search algorithm is O(n), where n is the size of the data set. Since the elements in the dataset need to be compared one by one, in the worst case, where the target element is at the last position in the dataset, the entire dataset needs to be traversed.

The linear search algorithm is simple and easy to understand and suitable for small data sets or when the data set is disordered, but it is less efficient for large data sets. In ordered data sets, other efficient search algorithms such as binary search may be more suitable to use.

(2) Algorithm principle

The principle of linear search algorithm is as follows:

  1. First, starting from the first element of the dataset, compare it with the target element.

  2. If the current element is equal to the target element, the search is successful and the position of the current element or other required information is returned.

  3. If the current element is not equal to the target element, continue looking for the next element.

  4. Repeat steps 2 and 3 until the target element is found or the entire data set is traversed.

  5. If the target element is not found after traversing the entire data set, the search fails.

(3) Example

Here is a Java example code using a basic search algorithm:

public class LinearSearch {
    
    
    public static int linearSearch(int[] arr, int target) {
    
    
        for (int i = 0; i < arr.length; i++) {
    
    
            if (arr[i] == target) {
    
    
                return i;  // 找到目标元素,返回其索引
            }
        }
        return -1;  // 未找到目标元素,返回-1
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 9, 1, 7, 4};
        int target = 7;
        int result = linearSearch(arr, target);
        if (result == -1) {
    
    
            System.out.println("目标元素不存在");
        } else {
    
    
            System.out.println("目标元素在索引" + result + "处");
        }
    }
}

In the above example code, linearSearchthe method uses a linear search algorithm to find the target element. It accepts an array of integers arrand a target element targetas input, and returns the index of the target element in the array, or -1 if the target element is not found. mainThe example in the method shows how to call linearSearchthe method to find element 7 in the array and print the corresponding message based on the returned result.

2. Half search/Binary search

(1) Introduction to algorithm

The binary search algorithm is an efficient search algorithm, provided that the data must be in order. It compares the target value with the middle element of the array and reduces the search range by half based on the comparison result. It repeats this process until the target element is found or it is confirmed that the target element does not exist.

The time complexity of the binary search algorithm is O(log n), where n is the size of the array. This is because each lookup reduces the search range by half, so log n comparisons are required in the worst case.

It should be noted that the binary search algorithm only works on ordered arrays. If the array is unordered, you need to sort the array first and then perform a binary search.

(2) Algorithm principle

The principle of the binary search algorithm is to compare the target value with the middle element of the array, and reduce the search range by half based on the comparison result. This process is repeated until the target element is found or the target element is confirmed not to exist.

Specific steps are as follows:

  1. Determine the left and right boundaries of the search range. Initially, the left boundary is the index of the first element of the array, and the right boundary is the index of the last element of the array.

  2. Calculate the index of the middle element of the search range (taking the average of the left and right boundaries).

  3. Compare the target value to the intermediate element:

    • If the target value is equal to the middle element, the target element is found and the index of the middle element is returned.
    • If the target value is smaller than the middle element, then the target element may be to the left of the middle element, and the right boundary is updated to be the index of the middle element minus 1.
    • If the target value is greater than the middle element, then the target element may be to the right of the middle element, and the left boundary is updated to be the index of the middle element plus 1.
  4. In the new search range, repeat steps 2 and 3 until the target element is found or it is confirmed that the target element does not exist (the left boundary is larger than the right boundary).

(3) Example

Here is a Java example using the binary search algorithm:

public class BinarySearch {
    
    
    public static int binarySearch(int[] arr, int target) {
    
    
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
    
    
            int mid = left + (right - left) / 2;
            
            if (arr[mid] == target) {
    
    
                return mid; // 找到目标元素,返回索引
            } else if (arr[mid] < target) {
    
    
                left = mid + 1; // 目标元素在右侧,更新左边界
            } else {
    
    
                right = mid - 1; // 目标元素在左侧,更新右边界
            }
        }

        return -1; // 目标元素不存在,返回-1
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
        int target = 23;
        int result = binarySearch(arr, target);
        
        if (result == -1) {
    
    
            System.out.println("目标元素不存在");
        } else {
    
    
            System.out.println("目标元素的索引为 " + result);
        }
    }
}

binarySearchIn the above example, a static method named is defined , which accepts a sorted array arrand the target value targetas parameters, and returns the index of the target value in the array (if it exists) or -1 (if it does not exist).

In binarySearchthe method, a loop is used whileto continuously narrow the search range until the target element is found or the target element is confirmed not to exist. In each loop, midthe target value is compared with the middle element by calculating the index of the middle element, and the left or right border is updated based on the comparison result.

In the method, an ordered array and a target value mainare defined , and then the method is called to search and the corresponding information is output based on the returned result.arrtargetbinarySearch

Running the above code, the output is:

目标元素的索引为 5

It indicates that the index of target element 23 in the array is 5.

3. Interpolation search

(1) Introduction to algorithm

The interpolation search algorithm is an improved binary search algorithm that finds the position of the target element in an ordered array. Compared with the binary search algorithm, the interpolation search algorithm improves the search speed by dynamically determining the search range based on the estimated position of the target value.

The idea of ​​the interpolation search algorithm is to estimate the approximate position of the target element in the array based on the comparison of the target element with the smallest element and the largest element in the array.

The time complexity of the interpolation search algorithm is O(log n), where n is the length of the array. When the search range is large and the elements are evenly distributed, the interpolation search algorithm is more efficient than the binary search algorithm. However, when the search range is small and the elements are unevenly distributed, the interpolation search algorithm may be less efficient than the binary search algorithm.

(2) Algorithm principle

The principle of the interpolation search algorithm is to estimate the approximate position of the target element in the array based on the comparison between the target element and the smallest element and the largest element in the array, thereby dynamically determining the search range and quickly locating the position of the target element.

The specific search process is as follows:

  1. Calculate the estimated position of the target element in the array. First, calculate the interpolation position through the linear interpolation formula: pos = left + (target - arr[left]) * (right - left) / (arr[right] - arr[left]). Among them, leftand rightrepresent the left and right boundaries of the current search range respectively, and targetrepresent the value of the target element. This formula estimates the position of a target element in an array based on a comparison between the target element and the smallest and largest elements in the array.

  2. If the target element is equal to the element at the estimated position, the target element is found and the estimated position is returned.

  3. If the target element is smaller than the element at the estimated position, it means that the target element is on the left, update the right boundary to the estimated position minus one, and then return to step 1.

  4. If the target element is larger than the element at the estimated position, it means that the target element is on the right side, update the left boundary to the estimated position plus one, and then return to step 1.

  5. If the left boundary is greater than the right boundary, the target element does not exist and -1 is returned.

(3) Example

The following is a Java example code using the interpolation search algorithm:

public class InterpolationSearch {
    
    
    public static int interpolationSearch(int[] arr, int target) {
    
    
        int left = 0;
        int right = arr.length - 1;

        while (left <= right && target >= arr[left] && target <= arr[right]) {
    
    
            if (left == right) {
    
    
                if (arr[left] == target)
                    return left;
                return -1;
            }

            int pos = left + (target - arr[left]) * (right - left) / (arr[right] - arr[left]);

            if (arr[pos] == target)
                return pos;

            if (arr[pos] < target)
                left = pos + 1;
            else
                right = pos - 1;
        }
        return -1;
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
     2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
        int target = 16;
        int result = interpolationSearch(arr, target);
        if (result == -1)
            System.out.println("Element not found");
        else
            System.out.println("Element found at index " + result);
    }
}

In this example, a interpolationSearchmethod is defined to perform the interpolation search algorithm. This method accepts a sorted array arrand the target element targetas parameters and returns the index of the target element, or -1 if the target element does not exist.

In interpolationSearchthe method, a loop is used to continuously update the search range. In each loop, the interpolation position is first calculated through the linear interpolation formula pos. Then, check the relationship between the element at the interpolation position and the target element. If they are equal, the target element is found and the interpolation position is returned. If the element at the interpolation position is smaller than the target element, it means that the target element is on the right side, and the left boundary is updated to the interpolation position plus one. If the element at the interpolation position is larger than the target element, it means that the target element is on the left, and the right boundary is updated to the interpolation position minus one. If the left boundary is greater than the right boundary, the target element does not exist and -1 is returned.

In the method, a sample array and target elements mainare defined , and then the method is called to perform the interpolation lookup algorithm. Finally, the search results are output based on the returned results.arrtargetinterpolationSearch

4. Fibonacci search

(1) Introduction to algorithm

The Fibonacci search algorithm is an optimization algorithm based on binary search, which uses the characteristics of the Fibonacci sequence to determine the search range.

The Fibonacci sequence is an infinite sequence where each number is the sum of the previous two numbers. Usually, the first few numbers of the Fibonacci sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

In the Fibonacci search algorithm, you first need to determine a Fibonacci sequence as the boundary of the search range. Then, based on the comparison results between the target element and the boundary element, the search scope is continuously narrowed.

The advantage of the Fibonacci search algorithm is that it is faster than binary search in some cases. It can effectively narrow the search scope and reduce the number of comparisons. However, the implementation of the Fibonacci search algorithm is relatively complex and requires additional space to store the Fibonacci sequence. Therefore, in practical applications, its use is relatively rare.

(2) Algorithm principle

The principle of the Fibonacci search algorithm is based on the characteristics of the Fibonacci sequence, which continuously narrows the search scope by dividing the array into two parts.

The algorithm steps are as follows:

  1. Initialize the first two elements of the Fibonacci sequence to be F[0] = 0 and F[1] = 1, and the next element of the Fibonacci sequence to be F[i] = F[i-1] + F [i-2].
  2. Find the smallest F[k] such that F[k] is greater than or equal to the length of the array. The Fibonacci sequence can be calculated by incrementing k.
  3. Initialize two pointers: left points to the starting position of the array, and right points to the end position of the array.
  4. Split the array into two parts using F[k] from the Fibonacci sequence. Set the pointer mid to the position of left plus F[k-1].
  5. Compare the target element with the element at the mid position of the pointer:
    • If the target element is equal to the element at mid position, the target element is found and mid is returned.
    • If the target element is smaller than the element at the mid position, the target element may be on the left part, and right is updated to mid-1.
    • If the target element is larger than the element at the mid position, the target element may be on the right side, and left is updated to mid+1.
  6. Repeat steps 4 and 5 until the target element is found or left is greater than right.

(3) Example

The following is Java example code for the Fibonacci finding algorithm:

public class FibonacciSearch {
    
    
    public static int fibonacciSearch(int[] arr, int target) {
    
    
        int n = arr.length;
        int fib2 = 0; // F(k-2)
        int fib1 = 1; // F(k-1)
        int fib = fib2 + fib1; // F(k)
        
        // 找到最小的斐波那契数列元素大于等于数组长度
        while (fib < n) {
    
    
            fib2 = fib1;
            fib1 = fib;
            fib = fib2 + fib1;
        }
        
        int offset = -1;
        
        while (fib > 1) {
    
    
            int i = Math.min(offset + fib2, n - 1);
            
            // 如果目标元素小于当前位置的元素,将查找范围缩小到左侧部分
            if (arr[i] > target) {
    
    
                fib = fib2;
                fib1 = fib1 - fib2;
                fib2 = fib - fib1;
            }
            // 如果目标元素大于当前位置的元素,将查找范围缩小到右侧部分
            else if (arr[i] < target) {
    
    
                fib = fib1;
                fib1 = fib2;
                fib2 = fib - fib1;
                offset = i;
            }
            // 找到目标元素
            else {
    
    
                return i;
            }
        }
        
        // 最后进行一次比较,查找最后一个元素
        if (fib1 == 1 && arr[offset + 1] == target) {
    
    
            return offset + 1;
        }
        
        return -1; // 目标元素不存在
    }
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    1, 3, 5, 7, 9, 11, 13};
        int target = 7;
        int index = fibonacciSearch(arr, target);
        
        if (index != -1) {
    
    
            System.out.println("目标元素 " + target + " 在数组中的索引为 " + index);
        } else {
    
    
            System.out.println("目标元素 " + target + " 不存在于数组中");
        }
    }
}

This sample code demonstrates how to use the Fibonacci search algorithm to find a target element in an ordered array. In this example, we set the target element to 7, and if the target element exists in the array, the index of the target element in the array will be printed. Otherwise, a message that the target element does not exist in the array is printed.

5. Block search

(1) Introduction to algorithm

The block search algorithm, also known as the block search algorithm, is a search algorithm suitable for situations where a set of ordered data is divided into multiple blocks. It combines the advantages of sequential search and binary search, aiming to improve search efficiency.

The basic idea of ​​the block search algorithm is to divide the data into multiple blocks and create an index for each block. The data within each block can be unordered, but the order between blocks is ordered. Usually, each block is equal in size, but it can also be divided into unequal sizes according to the actual situation.

When searching, first find the block where the target is based on the index, and then perform a sequential search or other search algorithm within the block until the target element is found or it is determined that the target element is not in the block.

The time complexity of the block search algorithm is O(sqrt(n)), where n is the total amount of data. Compared with the linear time complexity of sequential search O(n), block search is more efficient.

It should be noted that the chunked search algorithm is suitable for static data, that is, data that is not frequently inserted, deleted, or modified. If the data changes frequently, the index of the block needs to be rebuilt, which may lead to a decrease in the efficiency of the algorithm.

(2) Algorithm principle

The principle of the block search algorithm is as follows:

  1. Divide the data to be found into several blocks, each block containing a certain number of elements. The elements within each block can be unordered, but the order between blocks is ordered.

  2. Build an index of blocks, recording the start and end positions of each block. Typically an index table is used to store this information.

  3. According to the value of the target element, the block where the target element is located is found in the index table.

  4. A sequential search or other search algorithm is performed inside the found block until the target element is found or it is determined that the target element is not in the block.

  5. If the target element exists in the block, returns the position of the element; if the target element does not exist in the block, returns the non-existent mark.

(3) Example

Here is a Java example using the chunked search algorithm:

public class BlockSearch {
    
    
    
    // 分块查找算法
    public static int blockSearch(int[] arr, int target) {
    
    
        // 块的大小
        int blockSize = (int) Math.sqrt(arr.length);
        
        // 构建索引表
        int[] indexTable = new int[blockSize];
        for (int i = 0; i < blockSize; i++) {
    
    
            indexTable[i] = arr[i * blockSize];
        }
        
        // 在索引表中查找目标元素所在的块
        int blockIndex = 0;
        while (blockIndex < blockSize && target > indexTable[blockIndex]) {
    
    
            blockIndex++;
        }
        
        // 在找到的块内部进行顺序查找
        int start = (blockIndex == 0) ? 0 : (blockIndex - 1) * blockSize;
        int end = Math.min(blockIndex * blockSize, arr.length - 1);
        
        for (int i = start; i <= end; i++) {
    
    
            if (arr[i] == target) {
    
    
                return i;
            }
        }
        
        // 目标元素不存在
        return -1;
    }
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    3, 8, 14, 16, 20, 25, 30, 36, 42, 49, 55, 63, 68, 70, 78, 85, 92};
        int target = 36;
        
        int index = blockSearch(arr, target);
        
        if (index != -1) {
    
    
            System.out.println("目标元素 " + target + " 在数组中的位置为:" + index);
        } else {
    
    
            System.out.println("目标元素 " + target + " 不存在于数组中");
        }
    }
}

Running the above code will output:

目标元素 36 在数组中的位置为:7

In this example, the array is divided into chunks, each chunk is 4 in size. Then an index table is built to record the starting position of each block. Through the index table, you can quickly locate the block where the target element is located. A sequential search is performed inside the found block, and the location of the target element is finally found.

6. Extended block search

(1) Introduction to algorithm

The extended block search algorithm is improved on the basis of the traditional block search algorithm, and mainly includes the following expansions:

  1. The size of the block is not fixed: In the traditional block search algorithm, the size of each block is fixed. In the extended block search algorithm, the size of each block can be dynamically adjusted according to the actual situation. This can make the size of each block more appropriate according to the distribution of data and improve search efficiency.

  2. The ordering of elements within a block is not fixed: in the traditional block search algorithm, the elements within the block must be ordered. In the extended block search algorithm, different sorting methods can be selected according to specific needs. For example, you can use algorithms such as quick sort and merge sort to sort the elements within each block.

  3. The relationship between blocks is not fixed: In the traditional block search algorithm, blocks must be ordered. In the extended block search algorithm, the relationship between blocks can be determined according to the actual situation. For example, you can choose to use the largest element between blocks as an index table, or use other data structures to represent the relationships between blocks.

  4. Support dynamic data update: The traditional block search algorithm is mainly suitable for static data, that is, the data will not change. The extended block search algorithm can support dynamic data updates. When data changes, the orderliness of the data can be maintained by rebuilding the index table or adjusting the block size.

The extended block search algorithm can be flexibly adjusted according to actual needs to improve search efficiency and adapt to changes in dynamic data. It has high efficiency and flexibility in some specific scenarios, such as database indexing, search engines, etc.

(2) Algorithm principle

The principle of the extended block search algorithm can be summarized as the following steps:

  1. Divide into chunks: Divide the ordered array into chunks and determine the size of each chunk. The size of the block can be dynamically adjusted according to the actual situation, so that the size of each block is more suitable.

  2. Sorting within blocks: Sorts the elements within each block. You can choose different sorting algorithms, such as quick sort, merge sort, etc.

  3. Build an index table: Build an index table based on the relationship between blocks. The index table can choose to use the starting position of each block as the index, or select the largest element within the block as the index. The index table can be represented by data structures such as arrays and linked lists.

  4. Search operation: According to the element to be searched, find the corresponding block through the index table, and search within the block. You can use binary search, interpolation search, etc. to search within the block.

  5. Data update: When data changes, corresponding maintenance operations need to be performed. You can maintain data orderliness by rebuilding index tables, adjusting block sizes, etc.

The principle of the extended block search algorithm is mainly to divide the ordered array into multiple blocks, and use appropriate sorting and search methods within the blocks. By building index tables and flexibly adjusting block sizes, search efficiency can be improved and dynamic data updates can be supported. This algorithm has high efficiency and flexibility in some specific scenarios, and is suitable for large-scale data search and maintenance.

(3) Example

The following is a sample Java code that demonstrates the implementation of the extended block search algorithm:

import java.util.Arrays;

public class ExtendedBlockSearch {
    
    
    private int[] arr; // 有序数组
    private int blockSize; // 块的大小

    public ExtendedBlockSearch(int[] arr, int blockSize) {
    
    
        this.arr = arr;
        this.blockSize = blockSize;
    }

    public int search(int target) {
    
    
        int blockIndex = findBlock(target); // 找到目标元素所在的块索引
        if (blockIndex == -1) {
    
    
            return -1; // 目标元素不存在
        }

        int start = blockIndex * blockSize; // 块的起始位置
        int end = Math.min(start + blockSize, arr.length); // 块的结束位置

        // 在块内进行二分查找
        int index = Arrays.binarySearch(arr, start, end, target);
        if (index >= 0) {
    
    
            return index; // 目标元素存在,返回索引
        } else {
    
    
            return -1; // 目标元素不存在
        }
    }

    private int findBlock(int target) {
    
    
        // 使用线性查找找到目标元素所在的块索引
        for (int i = 0; i < arr.length; i += blockSize) {
    
    
            if (arr[i] > target) {
    
    
                return (i - blockSize) / blockSize;
            }
        }
        return (arr.length - 1) / blockSize; // 目标元素在最后一个块中
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    1, 4, 7, 9, 13, 16, 20, 24, 28, 30};
        int blockSize = 3;
        ExtendedBlockSearch search = new ExtendedBlockSearch(arr, blockSize);

        int target = 13;
        int index = search.search(target);
        if (index != -1) {
    
    
            System.out.println("找到目标元素 " + target + ",索引为 " + index);
        } else {
    
    
            System.out.println("未找到目标元素 " + target);
        }
    }
}

In this example, a class is defined ExtendedBlockSearchto implement the extended block search algorithm. arrAccepts an ordered array and the size of the block in the constructor blockSize. searchThe method is used to find the target element. First, find the block index according to the target element, and then use binary search to search within the block. findBlockMethod is used to linearly search the block index where the target element is located. In mainthe method, a sample object is created and the index of searchthe target element is found using the method target. Finally output the search results.

7. Hash search

(1) Introduction to algorithm

Hash search algorithm, also known as hash search algorithm, is an algorithm that implements search by mapping keywords to array indexes. It speeds up the search by building a hash table, reducing the time complexity of the search from O(n) to O(1).

The basic idea of ​​the hash search algorithm is to calculate a hash value (also called a hash code) based on the keyword through a hash function, and then use the hash value as the index of the array and store the keyword in the array. When a keyword needs to be found, the hash value is calculated through the hash function and the element at that index position is found in the array. If this position is empty, it means that the keyword does not exist; if this position is not empty, there may be a conflict (that is, multiple keywords have the same hash value), and further processing of the conflict is required.

There are two common ways to handle conflicts: chain address method and open address method. The chain address method uses a linked list to connect keywords with the same hash value, and each array location stores a pointer to the first keyword. The open address rule uses certain rules to find the next available array location until the target keyword is found or the array location is empty.

The advantage of the hash search algorithm is that it is fast and requires only one hash calculation and one array access to find the target element. It is suitable for scenarios where large amounts of data are quickly found, such as database indexes, caches, etc. However, it also has some disadvantages, such as hash conflicts that may cause performance degradation, additional space is required to store hash tables, and the design of hash functions may affect search efficiency.

In practical applications, hash search algorithms are often combined with other data structures and algorithms to achieve more efficient searches. For example, a hash table can be used to optimize the query operation of a binary search tree to achieve more efficient dictionary lookups.

(2) Algorithm principle

The principle of the hash search algorithm is as follows:

  1. Build a hash table: First, you need to create an array as a hash table. The size of the array is generally determined based on the amount of data and conflicts. Each array location is called a slot and is used to store a key.

  2. Hash function: Define a hash function that maps keys to array indices. The hash function should satisfy the following conditions:

    • For the same keyword, the hash function should ensure that the calculated hash value is the same.
    • The hash function should try to evenly distribute the keys to different slots in the array to reduce the probability of collisions.
  3. Hash value calculation and storage: Calculate the hash value of the keyword to be found through the hash function and store it in the corresponding slot of the hash table. If the slot is already occupied, the conflict needs to be handled.

  4. Conflict handling: When the hash values ​​of multiple keywords are the same, it is called a hash conflict. There are two common conflict resolution methods: chain address method and open address method.

    • Chain address method: Connect keywords with the same hash value into a linked list, and store the head pointer of the linked list in the slot. When a keyword needs to be found, the hash value is first calculated through the hash function, and then the linked list on the corresponding slot is traversed until the target keyword is found or the linked list ends.
    • Open address method: When a slot is occupied, the next available slot is found according to certain rules until the target keyword is found or the slot is empty. Common rules include linear detection, quadratic detection, double hashing, etc.
  5. Search operation: When a keyword needs to be found, the hash value is first calculated through the hash function and the corresponding slot is accessed. If the slot is empty, the keyword does not exist; if the slot is not empty, further conflict processing is required.

(3) Example

Here is a Java example code using a hash lookup algorithm:

import java.util.LinkedList;

public class HashSearch {
    
    

    private int size; // 哈希表的大小
    private LinkedList<Integer>[] hashTable; // 哈希表

    public HashSearch(int size) {
    
    
        this.size = size;
        hashTable = new LinkedList[size];
    }

    // 哈希函数,将关键字映射到数组索引
    private int hashFunction(int key) {
    
    
        return key % size;
    }

    // 插入关键字到哈希表
    public void insert(int key) {
    
    
        int index = hashFunction(key);
        if (hashTable[index] == null) {
    
    
            hashTable[index] = new LinkedList<>();
        }
        hashTable[index].add(key);
    }

    // 查找关键字是否存在
    public boolean search(int key) {
    
    
        int index = hashFunction(key);
        if (hashTable[index] != null) {
    
    
            for (int k : hashTable[index]) {
    
    
                if (k == key) {
    
    
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
    
    
        HashSearch hashSearch = new HashSearch(10);
        hashSearch.insert(1);
        hashSearch.insert(5);
        hashSearch.insert(8);

        System.out.println(hashSearch.search(1)); // 输出: true
        System.out.println(hashSearch.search(3)); // 输出: false
    }
}

In the above example, a hash table of size 10 is first created. A hash function is then used to map the key to the array index, and the key is inserted into the corresponding slot. Finally, by calling searchthe method, you can determine whether the key exists in the hash table. The output result trueindicates that the keyword exists, and the output result falseindicates that the keyword does not exist.

Guess you like

Origin blog.csdn.net/m0_62617719/article/details/132863703