forked from shivaylamba/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request shivaylamba#570 from jayprajapati47/master
Create Added Binary-Search.dart
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
void main() { | ||
List<int> arr = [0, 1, 3, 4, 5, 8, 9, 22]; | ||
int userValue = 3; | ||
int min = 0; | ||
int max = arr.length - 1; | ||
binarySearch(arr, userValue, min, max); | ||
} | ||
|
||
binarySearch(List<int> arr, int userValue, int min, int max) { | ||
if (max >= min) { | ||
print('min $min'); | ||
print('max $max'); | ||
int mid = ((max + min) / 2).floor(); | ||
if (userValue == arr[mid]) { | ||
print('your item is at index: ${mid}'); | ||
} else if (userValue > arr[mid]) { | ||
binarySearch(arr, userValue, mid + 1, max); | ||
} else { | ||
binarySearch(arr, userValue, min, mid - 1); | ||
} | ||
} | ||
return null; | ||
} | ||
|
||
/* | ||
Output | ||
min 0 | ||
max 7 | ||
min 0 | ||
max 2 | ||
min 2 | ||
max 2 | ||
your item is at index: 2 | ||
*/ |