Graphical algorithm--search algorithm

Table of contents

Find algorithm

1. Sequential search

2. Binary search

3. Interpolation search method

4. Fibonacci search method


Find algorithm

Search algorithms can be divided into the following two types according to the size of the data

  1. Internal search: Internal search refers to an algorithm that performs search operations in memory or internal storage. Internal lookup is suitable for situations where the data size is small, stored in memory, or accessed quickly. Common internal search algorithms include sequential search, binary search, interpolation search, etc.
  2. External search: External search refers to an algorithm that performs search operations in large-scale data collections or in auxiliary storage media such as external disks.

Whether the searched table or data has changed is divided into the following two types:

  1. Static search: Static search refers to a search operation performed without changing the data being searched. That is, the table or data being searched remains unchanged during the search process. Static search is suitable for situations where static or read-only data is searched. Once an index or table is created, search operations can be repeated without modifying the data. Common static search algorithms include sequential search, binary search, interpolation search, etc.
  2. Dynamic search: Dynamic search refers to a search operation performed when the data being searched may be modified during the search process. That is, the table or data being searched may be added, deleted, or updated during the search process. Dynamic search is suitable for scenarios where dynamic data is searched and it is necessary to respond to data changes in real time. Common dynamic search algorithms include binary search trees, AVL trees, red-black trees, etc. These tree structures can achieve efficient search and support the insertion and deletion of dynamic data.

1. Sequential search

Illustration:

Algorithm principle : Sequential search, also called linear search, is a basic search algorithm. It compares the sequence of elements to be found one by one until the target element is found or the entire sequence is traversed. Specific steps are as follows:

  • Starting from the first element of the sequence, it is compared with the target element in sequence.
  • If the current element is equal to the target element, the search is successful and the corresponding position is returned.
  • If the current element is not equal to the target element, continue to the next element for comparison.
  • If the target element is not found after traversing the entire sequence, the search fails.

Case code:

public class javaDemo1 {

    public static void main(String[] args) {
        int data[] = new int[100];
        int Target = 99;
        int TargetIndex = -1;
        Random random = new Random();

        for (int i=0;i< data.length;i++){
            data[i] = random.nextInt(100);
        }

//        循序查找
        for (int j=0;j< data.length;j++){
            if (data[j] == Target){
                TargetIndex = j;
                break;
            }
        }
        System.out.println(Arrays.toString(data));
        if (TargetIndex!= -1){
            System.out.println("找到数据啦,在第"+(TargetIndex+1)+"个数据处");
        }else {
            System.out.println("抱歉,并没有找到目标数据 喵");
        }

    }
}

Algorithm summary: The time complexity of sequential search is O(n), where n is the length of the sequence to be searched. Due to its simple and intuitive characteristics, it is suitable for small-scale data or unordered data collections.


2. Binary search

Illustration:

Algorithm principle: Binary search, also called half search, is an efficient search algorithm that requires that the sequence to be searched must be in order. It quickly locates the target element by continuously narrowing the search scope. Specific steps are as follows:

  • The first element and the last element of the ordered sequence are used as the left and right boundaries respectively.
  • Calculate the middle position mid and obtain the element in the middle of the sequence.
  • If the middle element is equal to the target element, the search is successful and the corresponding position is returned.
  • If the middle element is larger than the target element, the target element may be in the left half, and the narrowed range is the sequence from the left boundary to mid-1.
  • If the middle element is smaller than the target element, the target element may be in the right half, narrowing the range to the sequence from mid+1 to the right boundary.
  • Repeat the above steps until the target element is found or the search range is empty.

Case code:

public class javaDemo2 {

    public static void main(String[] args) {
        int data[] = new int[10];
//        目标值与目标值对应的下角标
        int Target = 3;
        int TargetIndex = -1;

//        二分法的下界与上界
        int low = 0;
        int high = data.length-1;
        int middle;
        Random random = new Random();

        for (int i=0;i< data.length;i++){
            data[i] = random.nextInt(10);
        }
//        形成有序数组
        Arrays.sort(data);
//        二分法查找
        while (low<=high){
            middle = (low+high)/2;
            if (data[middle]>Target){
                high = middle-1;
            }else if (data[middle]<Target){
                low = middle + 1;
            }else {
                TargetIndex = middle;
                break;
            }
        }

        System.out.println(Arrays.toString(data));
        System.out.println("目标值为"+Target);
        if (TargetIndex!= -1){
            System.out.println("找到数据啦,在第"+(TargetIndex+1)+"个数据处");
        }else {
            System.out.println("抱歉,并没有找到目标数据 喵");
        }

    }
}

Algorithm summary : The time complexity of binary search is O(log n), where n is the length of the sequence to be searched. This is more efficient since the search range is reduced by half each time.


3. Interpolation search method

Illustration:

Algorithm principle : The interpolation search method is an optimized search algorithm based on the dichotomy method. It searches based on the estimated position of the target element in the ordered sequence, thus improving the search speed. Specific steps are as follows:

  • Calculate the estimated position of the target element relative to the first and last elements, that is, calculate the interpolation position mid through the formula (target - arr[left]) / (arr[right] - arr[left]) * (right - left) + left.
  • If the interpolation position mid exceeds the range of the array, or the target element is smaller than the first element or larger than the last element, it means that the target element does not exist.
  • If the element at the interpolation position mid is equal to the target element, the search is successful and the corresponding position is returned.
  • If the element at the interpolation position mid is larger than the target element, the target element may be in the left half, and the narrowed range is the sequence from the left boundary to mid-1.
  • If the element at the interpolation position mid is smaller than the target element, the target element may be in the right half, and the range is reduced to the sequence from mid+1 to the right boundary.
  • Repeat the above steps until the target element is found or the search range is empty.

Case code:

public class InsertSerach {
    public static void main(String[] args) {
        int data[] = new int[10];
        int Target = 9;
        int TargetIndex = -1;

        int low = 0;
        int high = data.length-1;
        int middle;

        Random random = new Random();

        for (int i= 0;i< data.length;i++){
            data[i] = random.nextInt(10);
        }
//        实现数组排列有序
        Arrays.sort(data);
//        插入查找
        while (low<=high){
            middle = low + (high - low) * (Target - data[low]) / (data[high] - data[low]);
            if (data[middle]<Target){
                low = middle +1;
            }else if (data[middle]>Target){
                high= middle -1;
            }else {
                TargetIndex = middle;
                break;
            }
        }
        System.out.println(Arrays.toString(data));
        if (TargetIndex!= -1){
            System.out.println("找到数据啦,在第"+(TargetIndex+1)+"个数据处");
        }else {
            System.out.println("抱歉,并没有找到目标数据 喵");
        }
    }
}

Algorithm summary: The time complexity of the interpolation search method is O(log log n), where n is the length of the sequence to be searched. It works well for ordered sequences that are evenly distributed, but may not work well for sequences that are unevenly distributed.


4. Fibonacci search method

Illustration:

Algorithm principle: Fibonacci search method is an improved binary search algorithm, which uses the golden section principle to search. First, you need to create a Fibonacci sequence in which each element is the sum of the previous two elements.

When using the Fibonacci search method, you must first determine the length of a Fibonacci sequence so that the length is not less than the length of the array to be searched. Then, determine two Fibonacci values ​​- F(k)-1 and F(k-2)-1 - based on the length of the Fibonacci sequence.

Then, in the ordered array to be searched, the element at position F(k)-1 is used as the intermediate value for comparison:

  • If the target value is equal to the intermediate value, the search is successful and the corresponding position is returned.
  • If the target value is less than the middle value, the Fibonacci search continues on the left half of the middle value.
  • If the target value is greater than the middle value, the Fibonacci search continues on the right half of the middle value.

After each comparison, according to the narrowing of the search range, a new intermediate value is selected for the next comparison until the target value is found or the search range is empty.

Case code:

public class FibonacciSearch {
    public static void main(String[] args) {
        int data[] = new int[10];
        int Target = 9;
        int TargetIndex = -1;

        int low = 0;
        int high = data.length - 1;
        int middle = 0;

        Random random = new Random();

        for (int i = 0; i < data.length; i++) {
            data[i] = random.nextInt(10);
        }

        Arrays.sort(data);

        // 生成斐波那契数列
        int[] fibonacci = generateFibonacci(data.length);

        // 根据斐波那契数列确定数组长度的最接近值
        int length = getClosestFibonacciNumber(data.length);

        // 扩展数组长度至斐波那契数列长度
        int[] extendedData = Arrays.copyOf(data, length);
        for (int i = data.length; i < extendedData.length; i++) {
            extendedData[i] = extendedData[data.length - 1];
        }

        while (low <= high) {
            int k = fibonacci[middle - 1];

            if (Target < extendedData[middle]) {
                high = middle - 1;
                middle = low + k - 1;
            } else if (Target > extendedData[middle]) {
                low = middle + 1;
                middle = low + k;
            } else {
                TargetIndex = Math.min(middle, high);
                break;
            }
        }

        System.out.println(Arrays.toString(data));
        if (TargetIndex != -1) {
            System.out.println("找到数据啦,在第" + (TargetIndex + 1) + "个数据处");
        } else {
            System.out.println("抱歉,并没有找到目标数据 喵");
        }
    }

    // 生成斐波那契数列
    private static int[] generateFibonacci(int length) {
        int[] fibonacci = new int[length];
        fibonacci[0] = 1;
        fibonacci[1] = 1;
        for (int i = 2; i < length; i++) {
            fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
        }
        return fibonacci;
    }

    // 获取斐波那契数列中与数组长度最接近的数值
    private static int getClosestFibonacciNumber(int n) {
        int a = 0;
        int b = 1;
        while (b <= n) {
            int temp = b;
            b = a + b;
            a = temp;
        }
        return a;
    }
}

Algorithm summary: The advantage of Fibonacci search method over traditional binary search method is that it can approach the target value faster and avoid the integer overflow problem that occurs when taking intermediate values ​​in binary search. However, in some cases, the performance of Fibonacci search method may not be as good as binary search method, so in practical applications, it is necessary to choose an appropriate search algorithm according to the specific situation.


Guess you like

Origin blog.csdn.net/dogxixi/article/details/132532683