| reed@google.com | ac10a2d | 2010-12-22 21:39:39 +0000 | [diff] [blame] | 1 | /* |
| epoger@google.com | ec3ed6a | 2011-07-28 14:26:00 +0000 | [diff] [blame] | 2 | * Copyright 2010 Google Inc. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license that can be |
| 5 | * found in the LICENSE file. |
| reed@google.com | ac10a2d | 2010-12-22 21:39:39 +0000 | [diff] [blame] | 6 | */ |
| 7 | |
| reed@google.com | ac10a2d | 2010-12-22 21:39:39 +0000 | [diff] [blame] | 8 | #ifndef GrTBSearch_DEFINED |
| 9 | #define GrTBSearch_DEFINED |
| 10 | |
| tfarina@chromium.org | bbff208 | 2014-01-31 21:48:52 +0000 | [diff] [blame] | 11 | #include "SkTypes.h" |
| 12 | |
| reed@google.com | ac10a2d | 2010-12-22 21:39:39 +0000 | [diff] [blame] | 13 | template <typename ELEM, typename KEY> |
| 14 | int GrTBSearch(const ELEM array[], int count, KEY target) { |
| tfarina@chromium.org | f6de475 | 2013-08-17 00:02:59 +0000 | [diff] [blame] | 15 | SkASSERT(count >= 0); |
| reed@google.com | ac10a2d | 2010-12-22 21:39:39 +0000 | [diff] [blame] | 16 | if (0 == count) { |
| 17 | // we should insert it at 0 |
| 18 | return ~0; |
| 19 | } |
| rmistry@google.com | d6176b0 | 2012-08-23 18:14:13 +0000 | [diff] [blame] | 20 | |
| reed@google.com | ac10a2d | 2010-12-22 21:39:39 +0000 | [diff] [blame] | 21 | int high = count - 1; |
| 22 | int low = 0; |
| 23 | while (high > low) { |
| 24 | int index = (low + high) >> 1; |
| 25 | if (LT(array[index], target)) { |
| 26 | low = index + 1; |
| 27 | } else { |
| 28 | high = index; |
| 29 | } |
| 30 | } |
| rmistry@google.com | d6176b0 | 2012-08-23 18:14:13 +0000 | [diff] [blame] | 31 | |
| reed@google.com | ac10a2d | 2010-12-22 21:39:39 +0000 | [diff] [blame] | 32 | // check if we found it |
| 33 | if (EQ(array[high], target)) { |
| 34 | return high; |
| 35 | } |
| rmistry@google.com | d6176b0 | 2012-08-23 18:14:13 +0000 | [diff] [blame] | 36 | |
| reed@google.com | ac10a2d | 2010-12-22 21:39:39 +0000 | [diff] [blame] | 37 | // now return the ~ of where we should insert it |
| 38 | if (LT(array[high], target)) { |
| 39 | high += 1; |
| 40 | } |
| 41 | return ~high; |
| 42 | } |
| 43 | |
| 44 | #endif |