Pinch binary search

content

First, the realization principle

2. Graphical analysis

3. Programming implementation


First, the realization principle

lemma:

I believe that everyone has played such a game, guessing the number game.

Game rules: Randomly write a number within 1-100, let us guess the number, the referee will prompt each time you guess, whether the guess is correct, the relationship between the guessed number and the guessed number.

For example: write a 56

First guess: guess 50 Hint: less than the guessed number

Second guess: guess 75 Hint: bigger than the guessed number

The third guess: guess 62 Hint: bigger than the guessed number

Fourth guess: guess 56 Hint: guess right

The above search method uses binary search, do you understand?

That's it! ! !

Requirements for binary search : the array to be searched is ordered

2. Graphical analysis

Example: There is such an array, as shown below.

We first compare the Key (number to be checked) with the number of arr[mid].

If Key==arr[mid], then found.

If Key>arr[mid], it means that the searched number may be between [mid+1,right]

If Key<arr[mid], the number to be searched may be between [left, mid-1]

Then from the above array, let's look for Key=9

First lookup:

mid=(left+right)/2

arr[mid]<Key

left=mid+1;//Change the search interval

Second lookup:

mid=(left+right)/2

arr[mid]>Key

right=mid-1//Change the search interval

 Third lookup:

mid=(right+mid)/2

arr[mid]==Key

Search is over.

Example 2: I want to find 18 inside

First lookup:

mid=(left+right)/2

arr[mid]<Key

left=mid+1;

Second lookup:

mid=(left+right)/2

arr[mid]<Key

left=mid+1;

 Third lookup:

mid=(right+left)/2

arr[mid]<Key

left=mid+1

 Fourth lookup:

mid=(left+right)/2

Key>arr[mid]

left=mid+1

 We can see left>right so is it necessary to continue searching?

Of course not, because the array is ordered, there is no number greater than the left of left and number to the right of right, so there is no such number in this array.

Do you think it is very simple to see here? Easy!!!

3. Programming implementation

//找到了返回数组下标,找不到返回-1
int BinarySearch(int *arr,int Key,int n){
    int left=0;
    int right=n-1;
    while(left<=right){//left>right则找不到,
    int mid=(right+left)/2;//中间数
    if(arr[mid]==Key)
    return mid;
    else if(arr[mid]<Key)//条件成立查找区间改变到[mid+1,right]
    left=mid+1;
    else
    right=mid-1;//否则查找区间改变到[left,mid-1]
}
    return -1;//找不到返回-1
}

I'm not talented, don't spray it, you can leave a little love if you understand.

 goodbye! ! ! !

Guess you like

Origin blog.csdn.net/qq_52763385/article/details/122015217