blob: 01e97440a65135ab4511a537fb2767e2db865cfb [file] [log] [blame]
reed@google.comac10a2d2010-12-22 21:39:39 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * 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.comac10a2d2010-12-22 21:39:39 +00006 */
7
reed@google.comac10a2d2010-12-22 21:39:39 +00008#ifndef GrTBSearch_DEFINED
9#define GrTBSearch_DEFINED
10
tfarina@chromium.orgbbff2082014-01-31 21:48:52 +000011#include "SkTypes.h"
12
reed@google.comac10a2d2010-12-22 21:39:39 +000013template <typename ELEM, typename KEY>
14int GrTBSearch(const ELEM array[], int count, KEY target) {
tfarina@chromium.orgf6de4752013-08-17 00:02:59 +000015 SkASSERT(count >= 0);
reed@google.comac10a2d2010-12-22 21:39:39 +000016 if (0 == count) {
17 // we should insert it at 0
18 return ~0;
19 }
rmistry@google.comd6176b02012-08-23 18:14:13 +000020
reed@google.comac10a2d2010-12-22 21:39:39 +000021 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.comd6176b02012-08-23 18:14:13 +000031
reed@google.comac10a2d2010-12-22 21:39:39 +000032 // check if we found it
33 if (EQ(array[high], target)) {
34 return high;
35 }
rmistry@google.comd6176b02012-08-23 18:14:13 +000036
reed@google.comac10a2d2010-12-22 21:39:39 +000037 // 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