binary_search

感觉写程序最重要的有两点:一、理解算法本身的实现原理和过程;二、理解如何用程序语言将算法过程表达出来。

#include <stdio.h>

#define N 10

int a[N] = {0, 1, 2, 3, 3, 3, 6, 7, 8, 9};

int binary_search(int a[], int l, int r, int x)
{
        int i;

        if(l > r)
                return -1;

        i = (l + r) / 2;
        if(a[i] == x)
                return i;
        else if(a[i] < x)
                return binary_search(a, i+1, r, x);
        else // a[i] > x
                return binary_search(a, l, i-1, x);
}
int main()
{
        int x, i;
        x = 6;

        i = binary_search(a, 0, N-1, x);
        if(i >= 0)
                printf("%d is found at index %d\n",
                        x, i);
        else
                printf("%d is not found\n", x);

        return 0;
}

猜你喜欢

转载自blog.csdn.net/lichengyu/article/details/49391623
今日推荐