Back to home page

LXR

 
 

    


0001 /*
0002  * A generic implementation of binary search for the Linux kernel
0003  *
0004  * Copyright (C) 2008-2009 Ksplice, Inc.
0005  * Author: Tim Abbott <tabbott@ksplice.com>
0006  *
0007  * This program is free software; you can redistribute it and/or
0008  * modify it under the terms of the GNU General Public License as
0009  * published by the Free Software Foundation; version 2.
0010  */
0011 
0012 #include <linux/export.h>
0013 #include <linux/bsearch.h>
0014 
0015 /*
0016  * bsearch - binary search an array of elements
0017  * @key: pointer to item being searched for
0018  * @base: pointer to first element to search
0019  * @num: number of elements
0020  * @size: size of each element
0021  * @cmp: pointer to comparison function
0022  *
0023  * This function does a binary search on the given array.  The
0024  * contents of the array should already be in ascending sorted order
0025  * under the provided comparison function.
0026  *
0027  * Note that the key need not have the same type as the elements in
0028  * the array, e.g. key could be a string and the comparison function
0029  * could compare the string with the struct's name field.  However, if
0030  * the key and elements in the array are of the same type, you can use
0031  * the same comparison function for both sort() and bsearch().
0032  */
0033 void *bsearch(const void *key, const void *base, size_t num, size_t size,
0034           int (*cmp)(const void *key, const void *elt))
0035 {
0036     size_t start = 0, end = num;
0037     int result;
0038 
0039     while (start < end) {
0040         size_t mid = start + (end - start) / 2;
0041 
0042         result = cmp(key, base + mid * size);
0043         if (result < 0)
0044             end = mid;
0045         else if (result > 0)
0046             start = mid + 1;
0047         else
0048             return (void *)base + mid * size;
0049     }
0050 
0051     return NULL;
0052 }
0053 EXPORT_SYMBOL(bsearch);