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