查找算法

#include <stdio.h>
#include <assert.h>
#define FALSE 0
#if 1 //array method
int find(int array[], int length, int value)
{
    if(NULL == array || 0 == length)
        return FALSE;
    int index = 0;
    for(; index < length; index++) {
        if (value == array[index])
            return index;
    }

    return FALSE;
}
#else //pointer method
int find(int array[], int length, int value)
{
    if(NULL == array || 0 == length)
        return FALSE;
    
    int *start = array;
    int *end = array + length;
    while (start < end) {
        if (value == *start)
            return ((int)start - (int)array) / (sizeof(int));
        start++;
    }

    return FALSE;
}
#endif

int main(void)
{
    int array[10] = {1, 2};
    assert(1 == find(array, 10, 2)); //if assert() parameter is false, will be abort
    assert(FALSE == find(array, 10, 10));
    printf("%d\n", find(array, 10, 2));
    printf("%d\n", find(array, 10, 10));
    return 0;
}

编译输出:

kevin@kevin-virtual-machine:~/Documents/Test/C/find$ ./update_find 
1
0

 

posted on 2018-08-14 13:50  Garnett21  阅读(151)  评论(0编辑  收藏  举报