char* strcpy( char* dest, const char* src ), int binary_search(int *arr, int key, int n), 可能的实现

#include <stdio.h>
char* stringCopy( char* dest, const char* src )
{
    size_t i = 0;
    while (dest[i] = src[i++]);
    return dest;
}
int binary_search(int *arr, int key, int n)
{
    int i = n / 2;
    if (arr[i] < key)
    {
        for ( ++i; i < n; ++i)
        {
            if (arr[i] == key) return i;
        }
    }
    else
    {
        for (; i > -1; --i)
        {
            if (arr[i] == key) return i;
        }
    }
    return -1;
}
int main()
{
    char strBuf[100];
    char *ret = stringCopy(strBuf, "This is a test!\n这是一个测试!");
    printf("%s\n", strBuf);
    printf("%s\n", ret);
    int ints[] = { 1, 3, 5, 7, 9 };
    printf("%d\n", binary_search(ints, 5, sizeof ints / sizeof(int)));
    printf("%d\n", binary_search(ints, -1, sizeof ints/ sizeof(int)));
    printf("%d\n", binary_search(ints, 9, sizeof ints/ sizeof(int)));
    printf("%d\n", binary_search(ints, 3, sizeof ints/ sizeof(int)));
    return 0;
}

posted on 2018-02-27 13:02  布伊什  阅读(...)  评论(...编辑  收藏

统计