Sah*_*bov 0 java algorithm search binary-search
它的工作方式与您期望的一样.没问题.
public int find(long searchKey) {
int lowerBound = 0;
int upperBound = nElems - 1;
int currentIndex;
while(true) {
currentIndex = (lowerBound + upperBound) / 2;
if(a[currentIndex] == searchKey)
return currentIndex; // found it!
else if(lowerBound > upperBound)
return nElems; // can't find it
else { // so then divide range
if(a[currentIndex] < searchKey)
lowerBound = currentIndex + 1; // it's in upper half
else
upperBound = currentIndex - 1; // it's in lower half
} // end else divide range
} // end while loop
} // end find() method
Run Code Online (Sandbox Code Playgroud)这是使用线性搜索的原始insert()方法.很简单,对吧?
public void insert(long value) { // put element into array
int j;
for(j=0; j<nElems; j++) // find where it goes
if(a[j] > value) // (linear search)
break;
for(int k=nElems; k>j; k--) // move bigger ones up
a[k] = a[k-1];
a[j] = value; // insert it
nElems++; // increment size
} // end insert()
Run Code Online (Sandbox Code Playgroud)
我需要修改insert()方法以使用find()方法的二进制搜索算法.这是我到目前为止所提出的.显然它有问题,但我似乎无法找到问题.它完全不起作用,即不执行任何插入:
public int insertBS(long value) {
int lowerBound = 0;
int upperBound = nElems - 1;
int curIn;
while(true) {
curIn = (lowerBound + upperBound) / 2;
if(a[curIn] == value)
return curIn;
else if(lowerBound > upperBound)
return nElems;
else {
if(a[curIn] < value)
lowerBound = curIn + 1;
else
upperBound = curIn - 1;
}
for(int k=nElems; k>curIn; k--) // move bigger one up
a[k] = a[k-1];
a[curIn] = value;
nElems++;
}
}
Run Code Online (Sandbox Code Playgroud)
语言:Java
使用有序数组.