Рет қаралды 3,557
How to Do a Binary Search in C#
Greetings, today I am here with how to code a Binary Search in C#.
A binary search is a search algorithm that is used to find the position of a target value within a sorted array or list. Here's how it works in a simple way:
#1 Start with a sorted array or list of elements.
#2 Set the lower and upper bounds of the search range. Initially, the lower bound is the first element of the array and the upper bound is the last element.
#3 Calculate the midpoint of the search range by taking the average of the lower and upper bounds: midpoint = (lower_bound + upper_bound) / 2.
#4 Compare the target value with the value at the midpoint of the search range.
#5 If the target value is equal to the midpoint value, then the search is successful and the position of the target value in the array is the midpoint index.
#6 If the target value is less than the midpoint value, then update the upper bound to be one less than the midpoint index and repeat steps 3-5 on the new search range.
#7 If the target value is greater than the midpoint value, then update the lower bound to be one more than the midpoint index and repeat steps 3-5 on the new search range.
#8 Repeat steps 3-7 until either the target value is found or the search range becomes empty (i.e., lower bound is greater than upper bound). If the search range becomes empty, then the target value is not present in the array.
Binary search works by repeatedly dividing the search range in half until the target value is found or the search range becomes empty. This makes binary search a very efficient algorithm for searching in large arrays or lists.
Thanks for watchig this C# tutorial on how to do a Binary Search.
Why not subscribe to keep notified when I upload?
tinyurl.com/Su...
How to Do a Binary Search in C#