Changeset 90812 in webkit for trunk/Source/JavaScriptCore/wtf/StdLibExtras.h
- Timestamp:
- Jul 12, 2011, 5:39:52 AM (14 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/Source/JavaScriptCore/wtf/StdLibExtras.h
r90811 r90812 124 124 } 125 125 126 enum BinarySearchMode {127 KeyMustBePresentInArray,128 KeyMustNotBePresentInArray129 };130 131 126 // Binary search algorithm, calls extractKey on pre-sorted elements in array, 132 127 // compares result with key (KeyTypes should be comparable with '--', '<', '>'). 128 // Optimized for cases where the array contains the key, checked by assertions. 133 129 template<typename ArrayType, typename KeyType, KeyType(*extractKey)(ArrayType*)> 134 inline ArrayType* binarySearch(ArrayType* array, size_t size, KeyType key , BinarySearchMode mode = KeyMustBePresentInArray)130 inline ArrayType* binarySearch(ArrayType* array, size_t size, KeyType key) 135 131 { 136 // The array must contain at least one element (pre-condition, array does con tain key).137 // If the array contains onlyone element, no need to do the comparison.132 // The array must contain at least one element (pre-condition, array does conatin key). 133 // If the array only contains one element, no need to do the comparison. 138 134 while (size > 1) { 139 135 // Pick an element to check, half way through the array, and read the value. 140 136 int pos = (size - 1) >> 1; 141 137 KeyType val = extractKey(&array[pos]); 142 138 143 139 // If the key matches, success! 144 140 if (val == key) … … 154 150 } 155 151 156 // In case of BinarySearchMode = KeyMustBePresentInArray 'size' should never reach zero. 157 if (mode == KeyMustBePresentInArray) 158 ASSERT(size); 152 // 'size' should never reach zero. 153 ASSERT(size); 159 154 } 160 161 // In case of BinarySearchMode = KeyMustBePresentInArray if we reach this point 162 // we've chopped down to one element, no need to check it matches 163 if (mode == KeyMustBePresentInArray) { 164 ASSERT(size == 1); 165 ASSERT(key == extractKey(&array[0])); 166 } 167 155 156 // If we reach this point we've chopped down to one element, no need to check it matches 157 ASSERT(size == 1); 158 ASSERT(key == extractKey(&array[0])); 168 159 return &array[0]; 169 160 }
Note:
See TracChangeset
for help on using the changeset viewer.