blob: 8baa839681628b0ac091f717326f8fdbd5e70244 [file] [log] [blame]
Thomas Gleixnera10e7632019-05-31 01:09:32 -07001// SPDX-License-Identifier: GPL-2.0-only
Tim Abbott1a94dc32011-04-14 20:00:19 +02002/*
3 * A generic implementation of binary search for the Linux kernel
4 *
5 * Copyright (C) 2008-2009 Ksplice, Inc.
6 * Author: Tim Abbott <tabbott@ksplice.com>
Tim Abbott1a94dc32011-04-14 20:00:19 +02007 */
8
Paul Gortmaker8bc3bcc2011-11-16 21:29:17 -05009#include <linux/export.h>
Tim Abbott1a94dc32011-04-14 20:00:19 +020010#include <linux/bsearch.h>
Andrea Righi02106f82019-02-13 01:15:34 +090011#include <linux/kprobes.h>
Tim Abbott1a94dc32011-04-14 20:00:19 +020012
13/*
14 * bsearch - binary search an array of elements
15 * @key: pointer to item being searched for
16 * @base: pointer to first element to search
17 * @num: number of elements
18 * @size: size of each element
19 * @cmp: pointer to comparison function
20 *
21 * This function does a binary search on the given array. The
22 * contents of the array should already be in ascending sorted order
23 * under the provided comparison function.
24 *
25 * Note that the key need not have the same type as the elements in
26 * the array, e.g. key could be a string and the comparison function
27 * could compare the string with the struct's name field. However, if
28 * the key and elements in the array are of the same type, you can use
29 * the same comparison function for both sort() and bsearch().
30 */
31void *bsearch(const void *key, const void *base, size_t num, size_t size,
32 int (*cmp)(const void *key, const void *elt))
33{
Sergey Senozhatsky166a0f72017-07-10 15:52:01 -070034 const char *pivot;
Tim Abbott1a94dc32011-04-14 20:00:19 +020035 int result;
36
Sergey Senozhatsky166a0f72017-07-10 15:52:01 -070037 while (num > 0) {
38 pivot = base + (num >> 1) * size;
39 result = cmp(key, pivot);
Tim Abbott1a94dc32011-04-14 20:00:19 +020040
Sergey Senozhatsky166a0f72017-07-10 15:52:01 -070041 if (result == 0)
42 return (void *)pivot;
43
44 if (result > 0) {
45 base = pivot + size;
46 num--;
47 }
48 num >>= 1;
Tim Abbott1a94dc32011-04-14 20:00:19 +020049 }
50
51 return NULL;
52}
53EXPORT_SYMBOL(bsearch);
Andrea Righi02106f82019-02-13 01:15:34 +090054NOKPROBE_SYMBOL(bsearch);