The simplest algorithm------binary search method

 The words written in front

Hello everyone, my name is Xiaoxie. I hope it will be helpful to you after reading this. If there are any shortcomings, please criticize and correct me!

I hope I can share my learning and progress with you all!

Introduction:

I. Introduction

An algorithm is a set of instructions to accomplish a task. Any code fragment can be regarded as an algorithm. When facing different problems, using appropriate algorithms can improve the efficiency of the code. In one example in this article, using the right algorithm can even reduce the original 4 billion steps required to an urgent 32 steps ----- Isn't it shocking? But that’s what’s so fascinating about algorithms. Okay, without further ado, let’s get to the point------(the simplest algorithm) binary search method.

2. Binary search

  1. Ordinary search

If we want to find a word starting with M from a dictionary, we can check the dictionary from the beginning, starting with the first letter A, until we turn the page to the part whose first letter is M.

  For example, if I randomly think of a number between 1 and 100, every time you guess a number, I will tell you whether the number is too high or too low, or whether it is correct.

Suppose you start from 1 and guess upward one by one, and my number happens to be 100, then you will guess the correct answer after 100 guesses. Of course, this guessing method is the stupidest.

The guessing methods in the above two examples use the stupidest and longest time-consuming search method, which I call ordinary search; its time complexity is O(n). Similarly, when you use ordinary search, When using algorithm code to solve this series of problems, others can tell at a glance whether your code is good or bad and whether it is better than others using better algorithms.

 2. Better search method

Let's take guessing numbers as an example. If you start guessing from 50, I'll tell you that your guess is too small. Although you guessed wrong, you can eliminate half of the numbers in one go. You know that my number is not between 1-50. between. After that, you were guessing 75, and I told you to guess the bigger number, and you eliminated half of the numbers at once, and then you guessed 63, and so on until you guessed correctly. You guessed the middle number, so you could eliminate it every time. Half the number, this is the binary search method. No matter what number I have in mind, you can guess it correctly within seven moves because you can eliminate half of the number every time.

Taking the dictionary as an example again, assuming that the dictionary has a total of 240,000 words, using the ordinary search method requires up to 240,000 steps, while using the binary search method only takes up to 17 steps to find it. Isn't it much faster than ordinary search?

Generally speaking, for a list containing n elements (which of course must be ordered), binary search requires at most log2n steps, while simple search requires at most n steps.

3. Code implementation

Let's take a look at how to write code to perform binary search in C language

First, let's assume there is an array with ten elements (1-10), and the number x we ​​are looking for is 7

int arr[10]={1,2,3,4,5,6,7,8,9,10};//创建一个数组arr
int x=7;//我们要找的数字x,7

Determine what to look for

int left = 0;//左边界
int sz = (sizeof(arr) / sizeof(arr[0]));//数组的大小
int right = sz - 1;//右边界

After determining the range, perform a binary search

 // 二分查找
    while (left <= right)
    {
        int mid = (left + right) / 2; // 计算中间元素的下标
        if (arr[mid] > x) // 如果中间元素大于要查找的元素
        {
            right = mid - 1; // 缩小右边界
        }
        else if (arr[mid] < x) // 如果中间元素小于要查找的元素
        {
            left = mid + 1; // 缩小左边界
        }
        else // 找到了要查找的元素
        {
            printf("找到了,下标为%d", mid); // 输出下标
            break; // 结束循环
        }
    }

Compare the middle value to see if it is larger or smaller, and still find it, if the middle value is smaller

So the new left is equal to mid+1;

If the middle value is larger

So new right=mid-1

As we continue to compare with x, until left and right point to the same value and they are not equal, it means that the number Subscript output. The following is the complete code

#include <stdio.h>

int main()
{
    int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; // 定义一个包含10个元素的数组
    int x = 7; // 要查找的元素
    int left = 0; // 左边界
    int sz = (sizeof(arr) / sizeof(arr[0])); // 数组的大小
    int right = sz - 1; // 右边界

    // 二分查找
    while (left <= right)
    {
        int mid = (left + right) / 2; // 计算中间元素的下标
        if (arr[mid] > x) // 如果中间元素大于要查找的元素
        {
            right = mid - 1; // 缩小右边界
        }
        else if (arr[mid] < x) // 如果中间元素小于要查找的元素
        {
            left = mid + 1; // 缩小左边界
        }
        else // 找到了要查找的元素
        {
            printf("找到了,下标为%d", mid); // 输出下标
            break; // 结束循环
        }
    }

    // 判断是否找到
    if (left > right)
    {
        printf("找不到!"); // 输出未找到的提示
    }

    return 0;
}

4. Summary

The above is the entire content of the binary search method. Of course, we need to pay special attention to one thing. When using the binary search method, it must be orderedAs long as the list of elements is in an ordered list of elements, there are 4 billion elements. The ordinary search method requires at most 4 billion steps, while the binary search method only requires 32 steps (2 to the 32nd power is 4 billion), I hope that when you encounter similar problems with ordered element lists after reading this article, you can use the binary search method, which will make your The code is more efficient and more eye-catching. , please forgive me for any shortcomings, let us learn and grow together.

Guess you like

Origin blog.csdn.net/xiaoxie8023/article/details/133715786
Recommended