PTA答案(非标准)6-1 3.3 BinarySearch (15分)

6-1 3.3 BinarySearch (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.

#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 */

答案

int binsearch(int x, int v[], int n){
 if(n<100){
     for(int i=0;i<n;i++){
         if(v[i]==x) return i;
     }
     return -1;
 }
    //上面是小数据,下面的是大数据
    int low,high,mid,count=0,count1=0;
    low=0;
    high=n-1;
    while(low<high)    //査找范围不为0时执行循环体语句
    {
        
        mid=(low+high)/2;    //求中间位置
        if(x<v[mid])    //x小于中间值时
            high=mid-1;    //确定左子表范围
        else if(x>v[mid])    //x 大于中间值时
            low=mid+1;    //确定右子表范围
        else if(x==v[mid])    //当x等于中间值时,证明查找成功
        {
            return mid;
              
        }   
    }
  
        return -1;
}

修修补补写出来的,有简单方法大佬可联系我改善。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值