C language binary search/binary search

 

Table of contents

1. Ideas

Two, the code


Write code to find a specific number in an integer sorted array.
Requirement: If found, print the subscript of the number, if not found, output: not found.

If you use traversal to find, there are n elements that need to be found at most n times, and the calculation is too complicated

At this time, you can think of binary search (half search)

1. Thoughts:

If the number you are looking for is 7 and the subscript is 6

2. Code:

#include<stdio.h>
int main()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int k = 7;
	int left = 0;
	int right = 9;
	int flag = 0;
	while (left<=right)
	{
		int mid = (left + right) / 2;
		if (arr[mid] > k) right = mid - 1;
		else if (arr[mid] < k) left = mid + 1;
		else 
		{
			printf("找到了,下标为:%d \n", mid); flag = 1; break;
		}
	}
	if (flag == 0)
		printf("找不到\n");
	return 0;
}

Guess you like

Origin blog.csdn.net/outdated_socks/article/details/127949650