public int BinarySearch(int x)
{
//if (Attendees.Length == 0)
// return -1;
int mid = (Count/ 2) -1;
Student cur = new Student(x);
while (cur.CompareTo(Attendees[mid]) != 0)
{
int sCount = Count;
if (cur.CompareTo(Attendees[mid]) < 0)
{
int NCount = sCount / 2;
mid = NCount / 2 - 1;
}
if (cur.CompareTo(Attendees[mid]) > 0)
{
int Start = mid +1;
mid = (Start + sCount) / 2;
}
else
break;
cur = Attendees[mid];
}
if (cur.CompareTo(Attendees[x]) == 0)
return mid;
else
return -1;
}
Can anyone help me find out why my binary search isn’t working? I’m very new to programming so any help would be much appreciated. Thank you.
I think you didn’t really grasp what binary search is about. In your code you are searching at which position element
xis in an array – guess what? It’s at positionx!What binary search is about is to find out the index of an element. Soooo you need to search for a given
Student:This code may not work 100% as I haven’t tried it and wrote it off my head, but it will point you in the right direction. Now, use the debugger on this code and single step through it to see whether it works as expected.