/*1* A generic implementation of binary search for the Linux kernel2*3* Copyright (C) 2008-2009 Ksplice, Inc.4* Author: Tim Abbott <[email protected]>5*6* This program is free software; you can redistribute it and/or7* modify it under the terms of the GNU General Public License as8* published by the Free Software Foundation; version 2.9*/1011#include <linux/module.h>12#include <linux/bsearch.h>1314/*15* bsearch - binary search an array of elements16* @key: pointer to item being searched for17* @base: pointer to first element to search18* @num: number of elements19* @size: size of each element20* @cmp: pointer to comparison function21*22* This function does a binary search on the given array. The23* contents of the array should already be in ascending sorted order24* under the provided comparison function.25*26* Note that the key need not have the same type as the elements in27* the array, e.g. key could be a string and the comparison function28* could compare the string with the struct's name field. However, if29* the key and elements in the array are of the same type, you can use30* the same comparison function for both sort() and bsearch().31*/32void *bsearch(const void *key, const void *base, size_t num, size_t size,33int (*cmp)(const void *key, const void *elt))34{35size_t start = 0, end = num;36int result;3738while (start < end) {39size_t mid = start + (end - start) / 2;4041result = cmp(key, base + mid * size);42if (result < 0)43end = mid;44else if (result > 0)45start = mid + 1;46else47return (void *)base + mid * size;48}4950return NULL;51}52EXPORT_SYMBOL(bsearch);535455