Arrays.sol 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. import "./math/Math.sol";
  4. /**
  5. * @dev Collection of functions related to array types.
  6. */
  7. library Arrays {
  8. /**
  9. * @dev Searches a sorted `array` and returns the first index that contains
  10. * a value greater or equal to `element`. If no such index exists (i.e. all
  11. * values in the array are strictly less than `element`), the array length is
  12. * returned. Time complexity O(log n).
  13. *
  14. * `array` is expected to be sorted in ascending order, and to contain no
  15. * repeated elements.
  16. */
  17. function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  18. if (array.length == 0) {
  19. return 0;
  20. }
  21. uint256 low = 0;
  22. uint256 high = array.length;
  23. while (low < high) {
  24. uint256 mid = Math.average(low, high);
  25. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  26. // because Math.average rounds down (it does integer division with truncation).
  27. if (array[mid] > element) {
  28. high = mid;
  29. } else {
  30. low = mid + 1;
  31. }
  32. }
  33. // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
  34. if (low > 0 && array[low - 1] == element) {
  35. return low - 1;
  36. } else {
  37. return low;
  38. }
  39. }
  40. }