static int FindNumber(int[] array, int num)
{
int result = -1;
if (array == null)
{
return result;
}
for (int i = 0; i < array.Length - 1; i++)
{
if (array[i] > array[i + 1])
{
throw new Exception("input array is not sorted properly.");
}
}
for (int j = 0; j < array.Length; j++)
{
if (array[j] == num)
{
result = j;
}
}
return result;
}
static int FindNumber1(int[] array, int num)
{
int result = -1;
if (array == null)
{
return result;
}
for (int i = 0; i < array.Length -1; i++)
{
if (array[i] > array[i +1])
{
throw new Exception("input array is not softed properly.");
}
}
int low = 0;
int mid = 0;
int high = array.Length - 1;
while (low<=high)
{
mid = (low + high) / 2;
if (array[mid] == num)
{
result = mid;
break;
}
if (array[mid] < num)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return result;
}
测试用例
{1,2,3,4}, 3
{1,2,3,4}, 5
{1,2,3,4}, 1
{1,2,3,4}, 4
{2,1,3,4}, 3
{2,1,3,4}, 0
null , 1
{}, 1
{1,2,3........999...} , 323