Example of an ascending recursive sort for objects that contain an integer that does not use java built in features to do the heavy lifting for you :
List<Person> recursiveSort(List<Person> personnel) {
boolean changed = false;
for (int i=0; i<personnel.size()-1; i++) { // Do not use for each format in recursive methods
if (compare(personnel.get(i),personnel.get(i+1))>0) {
changed = true;
swap(personnel,i,i+1);
}
}
if (changed) return sort(personnel); // Recursive call
else return personnel;
}
int compare(Person p1, Person p2) {
if (p1.birthYear < p2.birthYear) return -1;
if (p2.birthYear < p1.birthYear) return 1;
return 0;
}
void swap(List<Person> personnel, idx1, idx2) {
try {
Person swp = personnel.get(idx1);
personnel.set(idx1, personnel.get(idx2));
personnel.set(idx2, swp);
catch (Exception e) {
// Print warning
}
}
I know how to sort integer arrays, but I'm not sure how when there is an ArrayList of objects involved.
Sorting an array of objects on a member integer attribute should be the exact same algorithm as sorting an array of integres, except that you need to access the integer attribute value. An example of this is :
Collections.sort(personnel,new Comparator() {
@Override
public int compare(Person p1, Person p2) {
if (p1.birthYear < p2.birthYear) return -1;
if (p2.birthYear < p1.birthYear) return 1;
return 0;
}
});