二分搜索实现

#include 

#define MAXSIZE 10

int binsearch(int val, int arr[], int size);

int main(int argc, char **argv) {
    int arr[MAXSIZE];
    for (int i = 0; i < MAXSIZE; ++i) {
        arr[i] = i;
    }
    printf("Please enter the value: \n");
    int val;
    scanf("%d", &val);

    int index = binsearch(val, arr, MAXSIZE);

    printf("The index is %d\n", index);

    return 0;

}

int binsearch(int val, int arr[], int size) {
    int start, end, mid;
    start = 0;
    end = size - 1;
    while (start < end) {
        mid = (start + end) / 2;
        if (val < arr[mid]) {
            end = mid - 1;
        } else if (val > arr[mid]) {
            start = mid + 1;
        } else {
            return mid;
        }
    }

    return -1;
}

你可能感兴趣的:(C程序设计语言)