52.1 重新实现 computeNearests。
52.2 增加 setDistanceMeasure() 方法。
52.3 增加 setNumNeighors() 方法。
/**
************************************
* Set numNeighbors.
*
* @param paraNeighbors
The num of Neighbors.
************************************
*/
public void setNumNeighors(int paraNeighbors) {
numNeighbors = paraNeighbors;
return;
}// Of setNumNeighors
/**
*
*********************
* @Title: adjustHeap
* @Description: TODO(Adjust the heap.)
*
* @param paraStartIndex The start of the index that need to adjust.
* @param paraLength The length of the adjusted sequence.
* @param paraDistances The array of distance.
* @param paraIndexes The index of distance.
*********************
*
*/
public void adjustHeap(int paraStartIndex, int paraLength, double[] paraDistances, int[] paraIndexes) {
int tempParentIndex = paraStartIndex;
double tempDistance = paraDistances[paraStartIndex];
int tempIndex = paraIndexes[paraStartIndex];
for (int i = paraStartIndex * 2 + 1; i < paraLength; i = i * 2 + 1) {
// Select the smaller.
if (i + 1 < paraLength && paraDistances[i + 1] < paraDistances[i])
i++;
if (tempDistance > paraDistances[i]) {
// Update the index and distance.
paraIndexes[tempParentIndex] = paraIndexes[i];
paraDistances[tempParentIndex] = paraDistances[i];
tempParentIndex = i;
} else {
break;
} // Of if
} // Of for i
paraDistances[tempParentIndex] = tempDistance;
paraIndexes[tempParentIndex] = tempIndex;
}// Of adjustHeap
/**
*
*********************
* @Title: selectWithHeap
* @Description: TODO(Select the nearest indices.)
*
* @param paraDistances The distance.
* @return A array of result.
*********************
*
*/
public int[] selectWithHeap(double[] paraDistances) {
int[] resultNearests = new int[numNeighbors];
// Initialize the indexes.
int[] tempIndexes = new int[trainingSet.length];
for (int i = 0; i < trainingSet.length; i++) {
tempIndexes[i] = i;
} // Of for i
// Build the heap.
int tempLength = paraDistances.length;
for (int i = trainingSet.length / 2 - 1; i >= 0; i--) {
adjustHeap(i, tempLength, paraDistances, tempIndexes);
}
for (int i = 0; i < numNeighbors; i++) {
resultNearests[i] = trainingSet[tempIndexes[0]];
tempIndexes[0] = tempIndexes[tempLength - i - 1];
paraDistances[0] = paraDistances[tempLength - i - 1];
adjustHeap(0, tempLength - i - 1, paraDistances, tempIndexes);
}
return resultNearests;
}// Of selectWithHeap
/**
*********************
* Set the distance measure
*
* @param paraDistanceMeasure
* The class of distance measure
* 0 symbolize MANHATTAN
* 1 symbolize EUCLIDEAN
*********************
*/
public void setDistanceMeasure(int paraDistanceMeasure) {
distanceMeasure = paraDistanceMeasure;
return;
}// Of setDistanceMeasure