Arrays.sol 1.4 KB

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