Skip to content

Instantly share code, notes, and snippets.

@Classy-Bear
Created May 26, 2024 15:43
Show Gist options
  • Save Classy-Bear/1bae894a210fa43a834c04249d172831 to your computer and use it in GitHub Desktop.
Save Classy-Bear/1bae894a210fa43a834c04249d172831 to your computer and use it in GitHub Desktop.
void main() {
var list = List.generate(1000, (x) => x + 1);
print('Binary search result: ${binarySearch(list, 213)}');
print('Binary search recursive result: ${binarySearchRecursive(list, 287)}');
}
/**
* Returns the index of the found [target].
*/
int? binarySearch(List<int> list, int target) {
var first = 0;
var last = list.length - 1;
while(first <= last) {
int midpoint = ((first + last) / 2).floor();
if (list[midpoint] == target) {
return midpoint;
} else if(list[midpoint] < target) {
first = midpoint + 1;
} else {
last = midpoint -1;
}
}
return null;
}
/**
* Returns true if the [target] is found.
*/
bool binarySearchRecursive(List<int> list, int target) {
if (list.isEmpty) return false;
int midpoint = (list.length / 2).floor();
if (list[midpoint] == target) return true;
if(list[midpoint] < target) return binarySearchRecursive(list.sublist(midpoint + 1), target);
return binarySearchRecursive(list.sublist(0, midpoint), target);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment