简体   繁体   中英

Sorting an array but changing the list of its coresponding array in order of the sort

For my program I need to declare 2 arrays. One of ids and the other of scores. each id has a corresponding score. I need to sort the scores from highest to lowest and print it in a table next to the scores id. I know how to sort the scores no problem. But i am unsure as to how to get the id's in the array to change in the same order as the scores. For example the score 312 was in index 4 before the sort. And the id 928 was in index 4. After the sort 312 is now in the index 13 but its corresponding id is still in index 4. How would I be able to fix it?

Edit: I would love not to use 2 arrays but I'm afraid its a requirement

Create a value object class that implements Comparable. Put them in an implementation of SortedSet.

If the assignment forces an implementation of two arrays, then you'll need to either:

1) manually sort one array and, as you're switching elements in the first array according to the search algorythm, you also switch the corresponding elements in the second array, or

2) Create a map of the associations between ith elements of the two arrays and use the map to recreate the 2nd array after sorting the first. Note that this works only if the elements in the sorted array are unique.

Just sort them at the same time using the same index. Here's an example with the infamous bubble sort:

int [] score = {5, 3, 6, 1, 2};
int [] id = {1, 2, 3, 4, 5};
for (int i = 0; i < id.length; i++)
{
     for (int j = 0; j < id.length-i-1; j++) 
     {
         if (score[j] < score[j+1])
         {
             int temp = score[j];
             score[j] = score[j+1];
             score[j+1] = temp;

             temp = id[j];
             id[j] = id[j+1];
             id[j+1] = temp;
         }
     }
}

The simple way is to use insertion sort, but it is not efficient enough, as its complexity is quadratic (N * N):

...
int[] ids = {4, 8, 5};
int[] values = {15, 30, 2};

for(int i = 1; i < values.length; i++) {
  for(int k = 0; k < i; k++) {
    if (values[k] > values[i]) {
      swapElements(values, k, i);
      swapElements(ids, k, i);
    }
  }
}
...
private static void swapElements(int[] array, int index1, int index2) {
  int temp = array[index1];
  array[index1] = array[index2];
  array[index2] = temp;
}

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