Sorting Two Arrays at a Time?

My problem is that I want to take an array and “reassign” indices so that you can list them from lowest to highest, without actually shuffling the original array. In this case it’s with student IDs and I want to be able to print them from lowest to shortest, but without shuffling so I can preserve the link between the IDs and the other info. This is what I have:

void setup(){
               
int [] students_id= {10001, 20001, 12334, 14332, 99999, 10111, 20101, 12034, 10332, 99991} ;

int[] indices = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
sort_records_by_id(indices, students_id);
println(indices);

}

void sort_records_by_id (int []indices, int []students_id) {
  
  int [] id_copy = students_id;
  
  // start at the beginning of the list and work down...
  for (int k = 1; k < id_copy.length; k++)
  {
    //swap the lower value with the one above it until no
    // more swapping is needed or beginning of list is
    // reached
    for (int j = k; j > 0 && id_copy[j] < id_copy[j - 1]; j-- )
    {
      int place_holder_id = id_copy[j];
      id_copy[j] = id_copy[j-1];
      id_copy[j-1] = place_holder_id;
      
      int place_holder_i = indices[j];
      indices[j] = indices[j-1];
      indices[j-1] = place_holder_i;
    }
  }
     println(id_copy);
}

However, this program seems to sort the ID_copy properly, but does not order the respective indices array properly. What am I doing wrong?

1 Like

Make a Student class w/ fields id & idx:

class Student {
  int id, idx;

  Student(int ident, int ind) {
    id = ident;
    idx = ind;
  }
}
1 Like

If I understand it correctly, you want to keep students_id without change, but sort the indices array based on the values in the students_id array.

To do that, in your sorting function, you need to use double indirection when comparing the values in the for loop condition, like this:

students_id[indices[j]] < students_id[indices[j - 1]]

Then you don’t need id_copy at all, you only swap values in the indices array as you are already doing.

Then you can print the student ids from lowest to highest like this:

println(student_ids[indices[0]]);
println(student_ids[indices[1]]);
...
1 Like