C language implementation of a non-recursive binary lookup algorithm (applicable to various types of data)

Source: Internet
Author: User

Using C language to implement a non-recursive binary lookup algorithm is not too difficult, but the requirements for a variety of data types general, the difficulty is somewhat increased.

C language has no function template, so the main use of void pointers and function pointers.

The specific code is as follows:

typedef int (*cmp_fun) (const void *key, const void *DST);
#define GET_DATA (arr, POS, size) (UINT8 *) (arr) + (POS) * (size)

void *bisearch (CONST void *ptable, UINT32 Cnt, UINT Size, VOID *key, Cmp_fun cmpfunc)
{
    INT32 Start, Mid, end;

    Start = 0;
    end = Cnt-1;
    
    if (Start > End) {return
        NULL;
    }
    While [start <= end] {
        Mid = (start + end)/2;
        if (Cmpfunc (Key, Get_data (ptable, Mid, Size) < 0) {end
            = Mid-1;
        }
        else if (Cmpfunc Key, Get_data (ptable, Mid, Size) > 0) {
            Start = Mid + 1;
        }
        else {return
            get_data (ptable, Mid, Size);
        }       
    }
    return NULL;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.