The Array class has a binary search:
int index = Array.BinarySearch(mynumbers, target);
In descending order, this can easily be done with ReverseComparer , which is easy to write like this:
public class ReverseComparer<T> : IComparer<T> { public int Compare(T x, T y) { return Comparer<T>.Default.Compare(y, x); } }
Then:
int index = Array.BinarySearch(numbers, 7, new ReverseComparer<int>());
If this is an academic exercise, and you should use a custom search, of course, this will not apply. If this is a special algorithm for the class, then the problems are that you have to exit the loop when it is detected, and the index is in mid , not in mynumbers[mid] :
//for a sorted array with descending values while (first<=last) { mid = (first + last) / 2; if (target < mynumbers[mid]) { first = mid + 1; } if (target > mynumbers[mid]) { last = mid - 1; } else { // the index is mid, not mynumbers[mid], and you need to break here // once found or it an infinite loop once it finds it. Label11.Text = "Target " + item + " was found at index " + mid; break; } }
And in fact, I would most likely set the bool flag to keep the algorithm clean and not mix find with output problems, this will also make it easier to talk about what happened if you exit the loop if not found:
bool found = false; //for a sorted array with descending values while (!found && first<=last) { mid = (first + last) / 2; if (target < mynumbers[mid]) { first = mid + 1; } if (target > mynumbers[mid]) { last = mid - 1; } else { // You need to stop here once found or it an infinite loop once it finds it. found = true; } } Label11.Text = found ? "Item " + item + " was found at position " + mid : "Item " + item + " was not found";
James Michael Hare
source share