TA的每日心情 | 衰 2021-2-2 11:21 |
---|
签到天数: 36 天 [LV.5]常住居民I
|
/**
* 递归的
* @param dataset
* @param data
* @param beginIndex
* @param endIndex
* @return
*/
public int halfFind(int[] dataset, int data, int beginIndex, int endIndex)
{
int midIndex=(beginIndex+endIndex)/2;
if(data<dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex)
{
return -1;
}
while(beginIndex<endIndex)
{
if(data<dataset[midIndex])
{
return halfFind(dataset, data, beginIndex, midIndex-1);
}
if(data>dataset[midIndex])
{
return halfFind(dataset, data, midIndex+1, endIndex);
}
if(data==dataset[midIndex])
{
return midIndex;
}
}
return -1;
}
/**
* 非递归
* @param dataset
* @param data
* @return
*/
public int halffind(int[] dataset, int data)
{
int beginIndex = 0;
int endIndex = dataset.length - 1;
int halfIndex = -1;
if (data < dataset[beginIndex] || data > dataset[endIndex] || beginIndex > endIndex)
{
return -1;
}
while (beginIndex < endIndex)
{
halfIndex = (beginIndex + endIndex) / 2;
if (dataset[halfIndex] < data)
{
beginIndex = halfIndex;
}
if (dataset[halfIndex] > data)
{
endIndex = halfIndex;
}
if (dataset[halfIndex] == data)
{
return halfIndex;
}
}
return -1;
}
|
|