I am trying to search a descending sorted array using this binary search code. However, after I sort it, and try to search, it doesn\'t come back with any result, just a loading
//this works fine with these Test cases
// has to check if (target == mynumbers[mid])
// this is for an array with ascending order.
class Program
{
static void Main(string[] args)
{
// TEST cases:
// for 8: item 8 was not found
// for 4: item 4 found at Position 3
// for 1: item 1 found at position 0
// for 0: item 0 was not found
int target =8;
int searchkey = target;
int[] mynumbers = { 1, 2, 3, 4, 5 };
int mid=0, first = 0, last = mynumbers.Length - 1;
bool found = false;
//for a sorted array with ascending values
while (!found && first <= last)
{
mid = (first + last) / 2;
if (target == mynumbers[mid])
found = true;
else
{
if (target > mynumbers[mid])
{
first = mid + 1;
}
if (target < mynumbers[mid])
{
last = mid - 1;
}
}
}
String foundmsg = found
? "Item " + searchkey + " was found at position " + mid
: "Item " + searchkey + " was not found";
Console.WriteLine(foundmsg);
}
}