简体   繁体   中英

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.

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;
 }

尝试将for循环更改为for(int i=0; max = distances.length && i < max; i++){...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM