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

2023-12-13 17:22:10

方法一:二分查找法

#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;
}

文章来源:https://blog.csdn.net/2301_80898911/article/details/134820100
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。