二分查找实现查找旋转数组中最小值,java实现,我的代码有什么问题?
/**
*
* 题目:旋转数组的最小数字
* 把一个数组最开始的若干个元素搬到数组的末尾,我们
* 称之为数组的旋转。输入递增排序的数组的一个旋转,
* 输出旋转数组的最小元素。
* @author solomon
*
*/
public class BinarySearch
{
public int min(int[] number)
{
//判断数组是否为空
if (null == number)
{
System.out.println("数组为空");
return 0;
}
int index1 = 0; //指向数组第一个元素的索引
int index2 = number.length - 1; //指向数组最后一个元素的索引
int indexMid = index1; //二分查找要指向的中间元素的索引,初始化为0
while (number[index1] >= number[index2])
{
if (1 == index1 - index2)
{
indexMid = index2;
break;
}
indexMid = (index1 + index2) / 2;
if (number[index1] == number[index2]
&& number[index1] == number[indexMid]
&& number[index2] == number[indexMid])
{
return minInOrder(number, index1, index2);
}
if (number[indexMid] >= number[index1])
{
index1 = indexMid;
}
if (number[indexMid] <= number[index2])
{
index2 = indexMid;
}
}
return number[indexMid];
}
//当number[index1],number[index2]和number[indexMid]相等的时候,需要使用顺序查找来找到最小值
public int minInOrder(int[] number, int index1, int index2)
{
int result = number[index1]; //要查找的值
for (int i=index1+1; i<=index2; i++)
{
if (result > number[i])
{
result = number[i];
}
}
return result;
}
}
public class BinarySearchTest
{
public static void main(String[] args)
{
BinarySearch search = new BinarySearch();
int[] number = new int[]{3,4,5,1,2};
int min = search.min(number);
System.out.println("数组中最小值为:" + min);
}
}
if (number[indexMid] >= number[index1])
{
index1 = indexMid;
}