377
378 // Binary search and insertion utility. Search array for element
379 // matching key according to the static compare function. Insert
380 // that element is not already in the list. Assumes the list is
381 // already sorted according to compare function.
382 template <int compare(const E&, const E&)> E insert_sorted(E& key) {
383 bool found;
384 int location = find_sorted<E, compare>(key, found);
385 if (!found) {
386 insert_before(location, key);
387 }
388 return at(location);
389 }
390
391 template <typename K, int compare(const K&, const E&)> int find_sorted(const K& key, bool& found) {
392 found = false;
393 int min = 0;
394 int max = length() - 1;
395
396 while (max >= min) {
397 int mid = (max + min) / 2;
398 E value = at(mid);
399 int diff = compare(key, value);
400 if (diff > 0) {
401 min = mid + 1;
402 } else if (diff < 0) {
403 max = mid - 1;
404 } else {
405 found = true;
406 return mid;
407 }
408 }
409 return min;
410 }
411 };
412
413 // Global GrowableArray methods (one instance in the library per each 'E' type).
414
415 template<class E> void GrowableArray<E>::grow(int j) {
416 // grow the array by doubling its size (amortized growth)
417 int old_max = _max;
|
377
378 // Binary search and insertion utility. Search array for element
379 // matching key according to the static compare function. Insert
380 // that element is not already in the list. Assumes the list is
381 // already sorted according to compare function.
382 template <int compare(const E&, const E&)> E insert_sorted(E& key) {
383 bool found;
384 int location = find_sorted<E, compare>(key, found);
385 if (!found) {
386 insert_before(location, key);
387 }
388 return at(location);
389 }
390
391 template <typename K, int compare(const K&, const E&)> int find_sorted(const K& key, bool& found) {
392 found = false;
393 int min = 0;
394 int max = length() - 1;
395
396 while (max >= min) {
397 int mid = (int)((uint)max + min) / 2;
398 E value = at(mid);
399 int diff = compare(key, value);
400 if (diff > 0) {
401 min = mid + 1;
402 } else if (diff < 0) {
403 max = mid - 1;
404 } else {
405 found = true;
406 return mid;
407 }
408 }
409 return min;
410 }
411 };
412
413 // Global GrowableArray methods (one instance in the library per each 'E' type).
414
415 template<class E> void GrowableArray<E>::grow(int j) {
416 // grow the array by doubling its size (amortized growth)
417 int old_max = _max;
|