C语言两种方法找寻数组的下标

方法一:二分查找法

#include<cstdio>
#include<iostream>
using namespace std;
int main()
{   
			int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
			int k = 6;//在数组中找到6
			int i = 0;
			int sz = sizeof(arr) / sizeof(arr[0]);
			int flat = 0;
			int left = 0;
			int right = sz-1;
			while (left <= right)
			{
				int mid = left + (right - left) / 2;
				if (arr[mid] < k)
				{
					left = mid + 1;
				}
				else if (arr[mid] > k)
				{
					right = mid - 1;
				}
				else
				{    
					flat = 1;
					printf("找到了,下标是%d\n", mid);
					break;
				}

			}
			if (flat == 0)
			{
				printf("找不到");
			}
return 0;
}

 

方法二:for循环

#include<cstdio>
#include<iostream>
using namespace std;
int main()
{   
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int k = 6;//在数组中找到6
	int i = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);
	int flat = 0;
	for (i = 0; i < sz; i++)
	{
		if (k == arr[i])
		{
			printf("找到了下标是%d", i);
			flat = 1;
			break;
		}
	}
	if (flat == 0)
	{
		printf("找不到了");
	}
	return 0;
}