Arrays.sol 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. pragma solidity ^0.5.2;
  2. import "../math/Math.sol";
  3. /**
  4. * @title Arrays
  5. * @dev Utility library of inline array functions
  6. */
  7. library Arrays {
  8. /**
  9. * @dev Upper bound search function which is kind of binary search algoritm. It searches sorted
  10. * array to find index of the element value. If element is found then returns it's index otherwise
  11. * it returns index of first element which is greater than searched value. If searched element is
  12. * bigger than any array element function then returns first index after last element (i.e. all
  13. * values inside the array are smaller than the target). Complexity O(log n).
  14. * @param array The array sorted in ascending order.
  15. * @param element The element's value to be find.
  16. * @return The calculated index value. Returns 0 for empty array.
  17. */
  18. function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  19. if (array.length == 0) {
  20. return 0;
  21. }
  22. uint256 low = 0;
  23. uint256 high = array.length;
  24. while (low < high) {
  25. uint256 mid = Math.average(low, high);
  26. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  27. // because Math.average rounds down (it does integer division with truncation).
  28. if (array[mid] > element) {
  29. high = mid;
  30. } else {
  31. low = mid + 1;
  32. }
  33. }
  34. // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
  35. if (low > 0 && array[low - 1] == element) {
  36. return low - 1;
  37. } else {
  38. return low;
  39. }
  40. }
  41. }