2022级统计计算机双学位《程序设计原理与C语言》上机作业

1035. 二分查找

单点时限: 2.0 sec

内存限制: 512 MB

Write a function binarySearch(a, n, x) that searches $x$ integer array $a$ of length $n$, and returns the index of $a$ ($-1$ if $x$ can not be found in $a$).

Assume elements of $a$ are entered in descending order, and the value of evey element is unique.

Write a program to call binarySearch(a, n, x).

/***************************************************************/
/*                                                             */
/*  DON'T MODIFY main function ANYWAY!                         */
/*                                                             */
/***************************************************************/

#include <stdio.h>

int binarySearch(int a[], int n, int x) {
    // TODO: your function definition
}

/***************************************************************/
#define N 100000
int a[N];
int main() {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    //********** binarySearch is called here *************
    int q, x;
    scanf("%d", &q);
    for (int i = 0; i < q; i++) {
        scanf("%d", &x);
        printf("%d\n", binarySearch(a, n, x));
    }
    //**************************************************
    return 0;
}

提示

Note that the function binarySearch(a, n, x) will be called many times in the test.