Using a selection sort to sort an array of objects?

ImprovingPants

This is a homework question, so I don't expect to have it done for me. That being said, I have ran into a problem. I understand selection sorting and can write a code that will do it for me, but I don't know how to access the specific part of the object that I need to sort. In this case, it is student ID numbers.

I have been given a partial program, a student class(creates students according to the values in another file we are given).

import TextIO.*;

public class StudentQEg {


static void sortByID(int[] A) {


for (int lastPlace = A.length-1; lastPlace > 0; lastPlace--) {   
  int maxLoc = 0;
  for (int j = 1; j <= lastPlace; j++) {
     if (A[j] > A[maxLoc]) {
        maxLoc = j;  
     }
  }
  int temp = A[maxLoc];
  A[maxLoc] = A[lastPlace];
  A[lastPlace] = temp;

 }

}

public static void main(String args[]){

StudentQ[] students;
int nbrstuds;
String name;
int id;
double avg;

TextIO.readUserSelectedFile();
nbrstuds=TextIO.getlnInt();

students=new StudentQ[nbrstuds];

for (int i=0; i<nbrstuds; i++) {
   name=TextIO.getWord();
   id=TextIO.getInt();
   avg=TextIO.getlnDouble();
   students[i]=new StudentQ(name,id,avg);
}

sortByID(students);

for (int i=0; i<nbrstuds; i++) {
   TextIO.putln(students[i]);
}

} 
}

This obviously throws the error that sortByID([int[]) isn't applicable for the args (StudentQ[]). Any attempt I have tried to reference StudentQ[].id has been unsuccessful, so any help is appreciated.

wns349

Why don't you just change the method signature from static void sortByID(int[] A) to static void sortByID(StudentQ[] students) ?

After changing the method signature, you can do something like this for comparison:

if (students[j].id > students[maxLoc].id)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related