user3004630
user3004630

Reputation: 27

Printing index and element of array

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

Answers (2)

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.

  • the most obvious way would be to have a second paralell array, and sort that along with your original array

example:

if (distances[i] < minVal) 
{
    double temp = distances[j];
    int tempindex = indices[j];
    ...
  • the better way would be to make a class with an index(or more appropriately named, an ID), and a value(which is your double), and sort an array of type Distance.

.

 Class Distance
 {
      public int ID;
      public double value;
 }

Upvotes: 1

Nate
Nate

Reputation: 35

Try change the for loop to for(int i=0; max = distances.length && i < max; i++){...}

Upvotes: -1

Related Questions