Skip to content

Instantly share code, notes, and snippets.

@a2468834
Last active April 17, 2022 10:07
Show Gist options
  • Save a2468834/e057a8337ab4c104b9f3cc951c895c6a to your computer and use it in GitHub Desktop.
Save a2468834/e057a8337ab4c104b9f3cc951c895c6a to your computer and use it in GitHub Desktop.
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.1;
contract SortedSequence {
uint256[100] public _array;
mapping(uint256 => bool) public _mapping;
function setValue(uint256[100] calldata init_seq) public {
for(uint8 i = 0; i < 100; i++) {
_array[i] = init_seq[i];
_mapping[init_seq[i]] = true;
}
}
}
contract BadSearch is SortedSequence {
function linSearch(uint256 target) public view returns (bool) {
for(uint256 i; i < _array.length; i++) {
if(_array[i] == target)
return true;
}
return false;
}
function binSearch(uint256 target) public view returns (bool) {
uint256 L;
uint256 H = _array.length - 1;
uint256 M;
if(_array[0] > target)
return false;
while(L <= H) {
M = (L + H) / 2;
if(_array[M] == target)
return true;
else if(_array[M] < target)
L = M + 1;
else // _array[M] > target
H = M - 1;
}
return false;
}
}
contract OkaySearch is SortedSequence {
function askMapping(uint256 target) public view returns (bool) {
return _mapping[target];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment