二分搜索实现

#include <stdio.h>

#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;
}
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页