michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=8 sts=2 et sw=2 tw=80: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #ifndef mozilla_BinarySearch_h michael@0: #define mozilla_BinarySearch_h michael@0: michael@0: #include "mozilla/Assertions.h" michael@0: michael@0: #include michael@0: michael@0: namespace mozilla { michael@0: michael@0: /* michael@0: * The algorithm searches the given container 'c' over the sorted index range michael@0: * [begin, end) for an index 'i' where 'c[i] == target'. If such an index 'i' is michael@0: * found, BinarySearch returns 'true' and the index is returned via the outparam michael@0: * 'matchOrInsertionPoint'. If no index is found, BinarySearch returns 'false' michael@0: * and the outparam returns the first index in [begin, end] where 'target' can michael@0: * be inserted to maintain sorted order. michael@0: * michael@0: * Example: michael@0: * michael@0: * Vector sortedInts = ... michael@0: * michael@0: * size_t match; michael@0: * if (BinarySearch(sortedInts, 0, sortedInts.length(), 13, &match)) michael@0: * printf("found 13 at %lu\n", match); michael@0: */ michael@0: michael@0: template michael@0: bool michael@0: BinarySearch(const Container &c, size_t begin, size_t end, T target, size_t *matchOrInsertionPoint) michael@0: { michael@0: MOZ_ASSERT(begin <= end); michael@0: michael@0: size_t low = begin; michael@0: size_t high = end; michael@0: while (low != high) { michael@0: size_t middle = low + (high - low) / 2; michael@0: const T &middleValue = c[middle]; michael@0: michael@0: MOZ_ASSERT(c[low] <= c[middle]); michael@0: MOZ_ASSERT(c[middle] <= c[high - 1]); michael@0: MOZ_ASSERT(c[low] <= c[high - 1]); michael@0: michael@0: if (target == middleValue) { michael@0: *matchOrInsertionPoint = middle; michael@0: return true; michael@0: } michael@0: michael@0: if (target < middleValue) michael@0: high = middle; michael@0: else michael@0: low = middle + 1; michael@0: } michael@0: michael@0: *matchOrInsertionPoint = low; michael@0: return false; michael@0: } michael@0: michael@0: } // namespace mozilla michael@0: michael@0: #endif // mozilla_BinarySearch_h