Arrays.sol 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. pragma solidity ^0.4.23;
  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 grater 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(
  19. uint256[] storage array,
  20. uint256 element
  21. )
  22. internal
  23. view
  24. returns (uint256)
  25. {
  26. if (array.length == 0) {
  27. return 0;
  28. }
  29. uint256 low = 0;
  30. uint256 high = array.length;
  31. while (low < high) {
  32. uint256 mid = Math.average(low, high);
  33. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  34. // because Math.average rounds down (it does integer division with truncation).
  35. if (array[mid] > element) {
  36. high = mid;
  37. } else {
  38. low = mid + 1;
  39. }
  40. }
  41. // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
  42. if (low > 0 && array[low - 1] == element) {
  43. return low - 1;
  44. } else {
  45. return low;
  46. }
  47. }
  48. }