blob: 08b0b85f357cb2bc032f93947b2b107d464b7fd2 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001
reed@google.comac10a2d2010-12-22 21:39:39 +00002/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00003 * 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.comac10a2d2010-12-22 21:39:39 +00007 */
8
9
epoger@google.comec3ed6a2011-07-28 14:26:00 +000010
reed@google.comac10a2d2010-12-22 21:39:39 +000011#ifndef GrTBSearch_DEFINED
12#define GrTBSearch_DEFINED
13
14template <typename ELEM, typename KEY>
15int GrTBSearch(const ELEM array[], int count, KEY target) {
tfarina@chromium.orgf6de4752013-08-17 00:02:59 +000016 SkASSERT(count >= 0);
reed@google.comac10a2d2010-12-22 21:39:39 +000017 if (0 == count) {
18 // we should insert it at 0
19 return ~0;
20 }
rmistry@google.comd6176b02012-08-23 18:14:13 +000021
reed@google.comac10a2d2010-12-22 21:39:39 +000022 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.comd6176b02012-08-23 18:14:13 +000032
reed@google.comac10a2d2010-12-22 21:39:39 +000033 // check if we found it
34 if (EQ(array[high], target)) {
35 return high;
36 }
rmistry@google.comd6176b02012-08-23 18:14:13 +000037
reed@google.comac10a2d2010-12-22 21:39:39 +000038 // 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