-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBinarySearch.sol
62 lines (51 loc) · 1.7 KB
/
BinarySearch.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;
/**
* @title Binary Search
* @notice The contract implements the binarySearch() function, which performs a search for an element in a sorted list
*/
contract BinarySearch {
uint256[] private _list;
/// @notice Return when the desired element is not found in the list
error None();
/// @notice Return when the size of the created list is zero
error ZeroSize();
constructor(uint256 size) {
if (size == 0) {
revert ZeroSize();
}
_createList(size);
}
/**
* @notice Binary search
* @param desiredValue The value being searched for
*/
function binarySearch(uint256 desiredValue) external view returns (uint256) {
/// Variables to store the boundaries of the list being searched
uint256 start = 0;
uint256 end = _list.length - 1;
/// Continue searching until the desired element is found
while (start <= end) {
uint256 middle = (start + end) / 2;
uint256 guessedValue = _list[middle];
if (guessedValue == desiredValue) {
return middle; /// Value found
}
if (desiredValue < guessedValue) {
end = middle - 1; /// The desired element is in the left half
} else {
start = middle + 1; /// The desired element is in the right half
}
}
revert None();
}
/**
* @notice Initialize a sorted list
* @param size The size of the sorted list to be created
*/
function _createList(uint256 size) private {
for (uint256 i = 0; i < size; i++) {
_list.push(i);
}
}
}