【Binary search】Detailed diagram

Table of contents

1. What is the binary search method?

2. Algorithm requirements

3. Algorithm thinking

Graphical diagram (the value of the number k to be found is 3)

 Reference Code


1. What is the binary search method?

Binary search is also called binary search (Binary Search), which is a more efficient search method. However, the binary search requires that the linear table must adopt a sequential storage structure, and the elements in the table are arranged in order according to the key. 

2. Algorithm requirements

1. Must be arranged in an orderly manner.

3. Algorithm thinking

For example, the sequence arr[]={1, 2, 3, 4, 5, 6, 7, 8, 9} searches for k=3;

The left, right, and mid records here are array subscripts

1. Use left to point to the leftmost number (1) in the sequence , that is, left=0;

2. Use right to point to the rightmost number (9) in the sequence , that is, right=8;

3. Use mid to record the number marked as (left+right)/2 , which is the number (5) in the middle of the array;

After this step is completed, the arr[] array is divided into two sub-arrays, separated by arr[mid]

That is: {1, 2, 3, 4} 5 {6, 7, 8, 9}

4. Use arr[mid] to compare with the size of the target number k , there are three situations

(1) arr[mid]=k ; that is, found

  (2) If k is greater than arr[mid] (that is, the number in the middle) , it means that the target number (k) is in the sub-array on the right , so it becomes to find the target element in the right array; the method is the same as above is similar, so we only need to change the left point to the leftmost element of the sub-array on the right, that is, left=mid+1;

  (3) Similarly, if k is smaller than arr[mid] , it means that the target number (k) is in the left sub-array , so it becomes to find the target element in the left array; we only to change the right point to It is the rightmost element of the sub-array on the left, that is, right=mid-1;

5. You only need to repeat the operation of the fourth step to find the position of the value of k;

Graphical diagram (the value of the number k to be found is 3)

 Reference Code

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10};
	int k = 0;
	scanf("%d",&k);
	int left = 0;
	int right = sizeof(arr) / sizeof(arr[0]) - 1;
	while (left < right)
	{
		int mid = (left + right)/2;
		if (arr[mid] == k)
		{
			printf("找到了,下标为%d\n",mid);
			break;
		}
		else if (arr[mid] < k)
		{
			left = mid + 1;
		}
		else
		{
			right = mid-1;
		}
	}
	if (left > right)
	{
		printf("没找到,数不在该数列上\n");
	}

	return 0;
}

output

 


!!!!

Guess you like

Origin blog.csdn.net/2301_77509762/article/details/131352203