Reputation: 27
Hey guys I'm really struggling with trying to print my array index and element value, I posted a question a few days ago and got really helpful advice but cannot seem to get this part right at all, I am able to print the 1st index of the array (distance) but not able to print the entire thing without losing the original index value:
double minVal = Double.MAX_VALUE;
int minIndex = -1;
for (int i=0, max=distances.length; i<max;i++) {
if (distances[i] < minVal) {
minVal = distances[i];
minIndex = i;
//Gets the minimum point and minimum distance
}
}
System.out.println("The Nearest to point K is point: "+minIndex+" with distance "+minVal);
Really sorry to keep bringing this matter up but really have tried and cannot get it to work for the life of me any help or advice would be appreciated.
Upvotes: 0
Views: 304
Reputation: 31184
First, you sort
for (int i=0; i<distances.length; i++) {
for(int j = i+1; j<distances.length; j++)
{
if (distances[i] > distances[j])
{
double temp = distances[j];
distances[j] = distances[i];
distances[i] = temp;
}
}
}
Then, you merely print
for (int i=0; i<distances.length; i++) {
System.out.println(i + " -> " + distances[i]);
}
If you want to keep the original indexes, you can do that too.
example:
if (distances[i] < minVal)
{
double temp = distances[j];
int tempindex = indices[j];
...
.
Class Distance
{
public int ID;
public double value;
}
Upvotes: 1
Reputation: 35
Try change the for loop to for(int i=0; max = distances.length && i < max; i++){...}
Upvotes: -1