Binary Search Array 2022 (Step-By-Step Breakdown)

preview_player
Показать описание
Binary Search Array 2022 (Step-By-Step Breakdown)

Рекомендации по теме
Комментарии
Автор

just an addition if you are trying to calculate midpoint it is better to do it this way int midpoint = start + (end-start)/2 to avoid stack overflow for large data sometimes adding two big integers together will exceed the maximum value that an INT can Hold

saaddev
Автор

if you put 5 as a search value on the example array with the implementation shown, it will create an infinite loop. That is because in some point start=2, end=3 and that will always make midpoint to 2.

in order to overcome this infinite loop, condition of the while loop can be changed to (start + 1 < end)

ardacetinkaya
Автор

Why don't we do something like below
if(arr[m]>value){
end=m-1;}

why to keep midpoint value in consideration anymore? shouldn't we just decrement end=m-1?

navdeepsingh-qncu
Автор

would it not be
end = intArray.Length - 1; ?

chadgregory
Автор

If start is zero, end should be 6 as we have 7 items in total.

navdeepsingh-qncu
Автор

using System;

namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
int[] array = { -22, -15, 2, 7, 20, 30, 54 };
Console.WriteLine(BinarySearch(array, 7));
}

static int BinarySearch(int[]arr, int val)
{
int start = 0;
int end = arr.Length - 1;

while (start < end)
{
int mid = (start + end) / 2;

if (arr[mid] == val)
{
return arr[mid];
}
if (arr[mid] < val)
{
start = mid + 1;
}
if (arr[mid] > val)
{
end = mid - 1;
}
}
return -1;
}
}
}

kvelez