7.2编写程序实现:输入10个数据,按从小到大用选择法排序,然后输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则打印出“无此数”。

#include
int main()
{
	int a[10];
	int i, j, t, min;
	int left = 0;
	int right = sizeof(a) / sizeof(a[0]);
	int key = 0;
	int mid;
	printf("请输入十个数:\n");
	for (i = 0; i < 10; i++)
		scanf("%d", &a[i]);

	for (i = 0; i < 10; i++)
	{
		min = a[i];
		for (j = i + 1; j < 10; j++)
		{
			if (a[j] < a[i])
			{
				t = a[i];
				a[i] = a[j];
				a[j] = t;
			}
		}
	}
	for (i = 0; i < 10; i++)
		printf("%d  ", a[i]);



	printf("请输入要查找的数字: ");

	scanf("%d", &key);

	// 二分查找

	while (left < right)

	{
		// 找到中间位置

		mid = left + ((right - left) >> 1);

		if (key == a[mid])

		{
			printf("%d\n", mid+1);

			break;

		}

		else if (key < a[mid])

		{
			right = mid;

		}

		else

		{
			left = mid + 1;

		}

	}

	if (left >= right)

		printf("无此数\n");

	return 0;

}

你可能感兴趣的:(安农21c语言,c语言,算法)