6-11 BinarySearch 二分查找法 c语言 (15 分)

Write a function to implement the binary search algorithm:

  • decide if a particular value x occurs in the sorted array v
  • the elements of v must be in increasing order
  • the function returns the position/index (a number between 0 and n-1) if x occurs in v, and -1 if not.

编写一个函数来实现二分查找法搜索算法:

确定排序数组v中是否出现特定值x

v的元素必须按递增顺序排列

如果x出现在v中,则函数返回位置/索引(0和n-1之间的数字),如果不出现,则返回-1。

Format of functions:

/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */
int binsearch(int x, int v[], int n)

Sample program of judge:

#include <stdio.h>

int binsearch(int x, int v[], int n);
int compare (const void * a, const void * b);

int main ()
{
    int n;    // size of array v
    int m;  // number of calling search 

    scanf("%d", &n);

    int * v = (int*)malloc(sizeof(int) * n);

    for(int i = 0; i < n; i++) {
        scanf("%d", &v[i]);
    }

    qsort(v, n, sizeof(int), compare); // to sort array v by calling standard library function

    scanf("%d", &m);

    while(m--) {
        int x;
        scanf("%d", &x);
        printf("%d\n", binsearch(x, v, n));
    }

    free(v);

    return 0;
}

int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

/* Your function(s) will be put here */

Sample Input:

5
3 2 1 5 4
3
6 3 2

结尾无空行

Sample Output:

-1
2
1

结尾无空行

关于二分查找法,网站上有专门的讲解,大家可以先去学习一下,便于理解。

总的来说,就是不断的把一段数据均分为两段,然后去判断这个数到底在哪个区间,直到找到这个数。所以二分查找法的一个重要条件是:元素必须按递增顺序排列

本题要求是如果有x这个数在里面,就返回这个数是第几个,比如第一个是,就返回1,第十个是,就返回10;如果不在里面就返回-1。

下面是代码,大家可以参考(这里二分查找法的好处是特别大的数据都能处理,如果单纯简单地去一个一个找,耗时太长,不好)。

int binsearch(int x, int v[], int n){
 int left, right, mid;
	left = 0;
	right = n - 1;
    //这里要求<=是因为当x正好等于中间那个数时left=right,所以如果只是小于号是无法运行的,必须有等号才行,这是一个不太好看出来的点
	while(left <= right) { 
		mid = ((left + right) / 2);	 
		if (x < v[mid]) {		
			right = (mid - 1);		
		}
		else if (x > v[mid]) {	
			left = (mid + 1);		
		}
		else if (x == v[mid]) {
            return mid;
		}
    }
         return -1;
	}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值