5 - Binary Search Algorithm Code in C#

preview_player
Показать описание
Binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array.
Binary search begins by comparing an element in the middle of the array with the target value.
If the target value matches the element, its position in the array is returned. If the target value is less than the element, the search continues in the lower half of the array.
If the target value is greater than the element, the search continues in the upper half of the array.
By doing this, the algorithm eliminates the half in which the target value cannot lie in each iteration.
We have discussed Binary Search algorithm code in C# in this video but logic is common for any programming language.

Time Complexity:
Best Case: O(1)
Average Case: O(log n)
Worst case: O(log n)
Space Complexity: O(1)
Рекомендации по теме
Комментарии
Автор

Awesome! Perfect explanation. Thank you sir.

sebastiancadena
Автор

Sir,

Can you please do a video on using BinarySearch() function built into C#. The C# function can handle strings, objects, lists etc etc as it has many overloaded functions into it. The simple example example goes like this:

using System;

namespace binarySearch
{
class Program
{
static void Main()
{
int[] IntArray = new int[15];
var random = new Random();

for (int i = 0; i < IntArray.Length; i++)
{
IntArray[i] = random.Next(100);
}

Array.Sort(IntArray);

foreach (var number in IntArray)
{
Console.Write($"{number, 4}");
}

Console.WriteLine();

Console.Write("Please enter a search item ");

int searchItem =

int position = Array.BinarySearch(IntArray, searchItem);
if (position >= 0)
Console.WriteLine($"Item {IntArray[position] } found at position {position + 1}.");
else
not found");
}
}
}

johnali
Автор

Is it possible to talk slowly so that we can understand you clearly. Thank you sir for the tutorial.

MrBloodman