Changeset 93466 in webkit for trunk/Source/JavaScriptCore/wtf/StdLibExtras.h
- Timestamp:
- Aug 19, 2011, 7:17:49 PM (14 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/Source/JavaScriptCore/wtf/StdLibExtras.h
r93039 r93466 131 131 // Binary search algorithm, calls extractKey on pre-sorted elements in array, 132 132 // compares result with key (KeyTypes should be comparable with '--', '<', '>'). 133 template<typename Array Type, typename KeyType, KeyType(*extractKey)(ArrayType*)>134 inline Array Type* binarySearch(ArrayType* array, size_t size, KeyType key, BinarySearchMode mode = KeyMustBePresentInArray)133 template<typename ArrayElementType, typename KeyType, KeyType(*extractKey)(ArrayElementType*)> 134 inline ArrayElementType* binarySearch(ArrayElementType* array, size_t size, KeyType key, BinarySearchMode mode = KeyMustBePresentInArray) 135 135 { 136 136 // The array must contain at least one element (pre-condition, array does contain key). … … 169 169 } 170 170 171 // Modified binarySearch() algorithm designed for array-like classes that support 172 // operator[] but not operator+=. One example of a class that qualifies is 173 // SegmentedVector. 174 template<typename ArrayElementType, typename KeyType, KeyType(*extractKey)(ArrayElementType*), typename ArrayType> 175 inline ArrayElementType* genericBinarySearch(ArrayType& array, size_t size, KeyType key) 176 { 177 // The array must contain at least one element (pre-condition, array does conatin key). 178 // If the array only contains one element, no need to do the comparison. 179 size_t offset = 0; 180 while (size > 1) { 181 // Pick an element to check, half way through the array, and read the value. 182 int pos = (size - 1) >> 1; 183 KeyType val = extractKey(&array[offset + pos]); 184 185 // If the key matches, success! 186 if (val == key) 187 return &array[offset + pos]; 188 // The item we are looking for is smaller than the item being check; reduce the value of 'size', 189 // chopping off the right hand half of the array. 190 if (key < val) 191 size = pos; 192 // Discard all values in the left hand half of the array, up to and including the item at pos. 193 else { 194 size -= (pos + 1); 195 offset += (pos + 1); 196 } 197 198 // 'size' should never reach zero. 199 ASSERT(size); 200 } 201 202 // If we reach this point we've chopped down to one element, no need to check it matches 203 ASSERT(size == 1); 204 ASSERT(key == extractKey(&array[offset])); 205 return &array[offset]; 206 } 207 171 208 } // namespace WTF 172 209
Note:
See TracChangeset
for help on using the changeset viewer.