I have to search a for a name from the array through binary search but, show the corresponding age of the person's name instead. Please no other suggestions, I have to do it with Binary search on 2D arrays.
string[,] persons = new string[4, 2];
persons[0, 0] = "Ana";
persons[0, 1] = "19";
persons[1, 0] = "Ammara";
persons[1, 1] = "20";
persons[2, 0] = "Marilyn";
persons[2, 1] = "40";
persons[3, 0] = "Zacharaia";
persons[3, 1] = "70";
string x = "Zacharia";
int upBound = persons.GetLength(0) - 1;
int lowBound = 0;
while (lowBound <= upBound)
{
int midpoint = lowBound + (upBound - lowBound) / 2;
int result = x.CompareTo(persons[midpoint, 1]);
if (result == midpoint)
{
Console.WriteLine("The value is present at:" + persons[midpoint, 1]);
break;
}
else if (result > midpoint)
{
lowBound = midpoint + 1;
Console.WriteLine("The value is present at:" + persons[lowBound, 1]);
break;
}
else if (result < midpoint)
{
upBound = midpoint - 1;
Console.WriteLine("The value is present at:" + persons[upBound, 1]);
break;
}
}
This code is showing the age of everyone 20. The CompareTo()
method is not working.