二分查找与常用选择排序

设有一整型查找表,利用二分查找法查找指定的关键字。

假设给出的查找表不确定是否排序,要求查找前,对查找表进行排序。

【输入形式】

输入若干组数据,每组数据包括:

(1)输入整数n,表示查找表长度为n(n小于1000);

(2)输入n个整数;

(3)输入查找关键字key。

【输出形式】

若找到,输出关键字的位置序号(排序后的位置)及查找次数;

若未找到,输出“no”及查找次数。

【样例输入】
11

5 13 19 21 37 56 64 75 80 88 92

21

11

5 13 19 21 37 56 64 75 80 88 92

85

5

36 12 48 55 84

36

5

63 -9 54 12 100

55

【样例输出】

4 [3]

no [3]

2 [3]

no [2]*/

int  binarySearch(int  list[], int  n, int  key, int  *count)
{
	int low, mid, high;
	int temp = 1;
	low = 0; high = n-1;
	while (low <= high)
	{
		mid = (low + high) / 2;
		if (key == list[mid])
		{
			*count = temp;
			return mid;
		}

		if (key<list[mid])
			high = mid - 1;
		else low = mid + 1;
		temp++;
	}
	*count = temp-1;
	return -1;

}

void sort(int list[], int n)
{
	int i, j, k, temp;
	for (i = 0; i < n - 1; i++)
	{
		k = i;
		for (j = i + 1; j <n; j++)
		if (list[j] < list[k])k = j;//找相对最小的那一个数
		if (i != k)//最小的不是当前数
		{
			temp = list[i];
			list[i] = list[k];
			list[k] = temp;
		}
	}
}

int  main()
{
	int  i, n, key, count = 0;
	int  a[MAX];
	while (scanf_s("%d", &n) == 1)
	{
		for (i = 0; i < n; i++)
		{
			scanf_s("%d", &a[i]);
		}
		sort(a, n);
		scanf_s("%d", &key);
		if ((i = binarySearch(a, n, key, &count)) >= 0)
		{
			printf("%d  [%d]\n", i + 1, count);//return i 是位置 
		}
		else
		{
			printf("no  [%d]\n", count);
		}
	}
	return  0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值