c语言-数组-搜索

数组搜索

线性搜索

搜索数组中数据并找到它在哪里(匹配数组第一个数据即可)

#include 
int search(int key,int a[],int len) {
	int ret = -1;
	for (int i = 0; i < len; i++)
	{
		if (key ==a[i]) {
			ret = i;
			break;
		}
	}
	return ret;
}
int main()
{
	int a[] = { 1,2,3,5,6,3,19 };
	int r = search(3, a,sizeof(a)/sizeof(a[0]));
	printf("%d",r);
	return 0;
}

二分法搜索

要求必须是有序数组,这里以数组a[] = { 1,2,3,5,6,7,19,37,89,101,111,119 }为例

搜索37所在下标

#include 
int search(int key, int a[], int len) {
	int ret = -1;
	int left = 0;
	int right = len - 1;
	while (left<=right)
	{
		int mid = (left + right) / 2;
		if (a[mid] == key) {
			ret = mid;
			break;
		}
		else if (a[mid]<key)
		{
			left = mid + 1;
		}
		else
		{
			right = mid - 1;
		}
	}
	return ret;
}
int main()
{
	int a[] = { 1,2,3,5,6,7,19,37,89,101,111,119 };
	int r = search(37, a, sizeof(a) / sizeof(a[0]));
	printf("%d", r);
	return 0;
}

你可能感兴趣的:(c/c++,数组,c语言,算法,数据结构)