lkml.org 
[lkml]   [2013]   [Jul]   [9]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
Patch in this message
/
From
Subject[PATCH v2] lib: One less subtraction in binary search iterations.
Date
The subtraction is removed at the expense of generality: when the element size
is 1, the array length cannot exceed half the architecture's addressable
memory.

Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
---
lib/bsearch.c | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/lib/bsearch.c b/lib/bsearch.c
index e33c179..668ae6c 100644
--- a/lib/bsearch.c
+++ b/lib/bsearch.c
@@ -24,6 +24,11 @@
* contents of the array should already be in ascending sorted order
* under the provided comparison function.
*
+ * There is a limitation when @size is 1: in this case @num must be at
+ * most SIZE_MAX / 2; that is, the number of elements in the sorted
+ * array must be at most half the maximum number expressible as a size_t
+ * to avoid overflows.
+ *
* Note that the key need not have the same type as the elements in
* the array, e.g. key could be a string and the comparison function
* could compare the string with the struct's name field. However, if
@@ -37,7 +42,7 @@ void *bsearch(const void *key, const void *base, size_t num, size_t size,
int result;

while (start < end) {
- size_t mid = start + (end - start) / 2;
+ size_t mid = (start + end) / 2;

result = cmp(key, base + mid * size);
if (result < 0)
--
1.7.9.5


\
 
 \ /
  Last update: 2013-07-10 23:28    [W:3.415 / U:0.004 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site