zoukankan      html  css  js  c++  java
  • 1-find

    查找算法

    #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
    ", find(array, 10, 2));
        printf("%d
    ", find(array, 10, 10));
        return 0;
    }

    编译输出:

    kevin@kevin-virtual-machine:~/Documents/Test/C/find$ ./update_find 
    1
    0
  • 相关阅读:
    向内的寻找
    了解潜意识
    NOI2014 Day1
    NOI2011 Day1
    NOI2012 Day2
    NOI2012 Day1
    NOI2013 Day2
    NOI2013 Day1
    拉格朗日乘数法
    NOI2015 Day2
  • 原文地址:https://www.cnblogs.com/debruyne/p/9474187.html
Copyright © 2011-2022 走看看