Implementing binary search of sorted array in C language

Principle. Binary search, also known as halved search, is only applicable to sorted arrays. . The principle of binary search is very simple, and the search efficiency for sorted arrays is also very high. . The specific principle is to compare the target value k each time) with the data in the middle of the array (represented by a [mid] below, and mid represents the index value of the middle position of the array). If k is greater than a [mid], continue to k Compare with a value greater than the middle of the a[mid] part; if k is less than a[mid], continue to compare k to the value of the middle of the a[mid] part. . Note: For unordered arrays, if you sort first, and then use binary search, although this method can achieve search, it will change the element position of the most primitive array, so for unordered arrays, it is best to use the basic search algorithm to achieve

#include<stdio.h>
int main()
{
	int a[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13 };
	int left = a[0];
	int sz = sizeof(a) / sizeof(a[0]);      //计算数组大小
	int right = a[sz - 1];    //使右值等于最后一个数字
	int k = 12;           //要查找的数是12
	int mid;
	while (left<=right)       //当左值小于=右值的时候进入循环,左值大于右值退出循环
	{
		 mid = (right + left) / 2;// 中间值等于左值加右值再除2
		if (k < mid)
		{
			right = mid-1;           //如果要找的数字小于mid,使右值等于mid-1
		}
		else if (k > mid)
		{
			left = mid + 1;      //如果要找的数字大于mid,使左值等于mid+1
		}
		else
		{
			printf("找到了,下标是:%d", mid - 1);    //如果要找的数字等于mid则找到了
			break;
		}
	}
	if (left > right)      //当左值大于右值时,就说明找不到
		printf("找不到");
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_49449676/article/details/124212324