Why don't you pass a student array to the method instead and do the comparison as array[i].gpa > array[j + 1].gpa
? (Note that you might have to provide a getter to access gpa
).
A more flexible way would be the use of either the Comparable
interface or a Comparator
, much like Collections.sort(...)
does.
public static <T extends Comparable<T>> void sort( int n, T[] array ) {
T tempVar;
for( int i = 0; i < n - 1; i++ ) {
for( int j = 0; j < n - 1; j++ ) {
if( array[i].compareTo( array[j + 1]) > 0 ) {
tempVar = array[j + 1];
array[j + 1] = array[i];
array[i] = tempVar;
}
}
}
}
class Student implements Comparable<Student> {
public int compareTo( Student s ) {
//compare gpa here
}
}
With a comparator you wouldn't have to implement Comparable
but provide a suitable instance of Comparator<Student>
, e.g.
public static <T> void sort( int n, T[] array, Comparator<T> comparator ) {
T tempVar;
for( int i = 0; i < n - 1; i++ ) {
for( int j = 0; j < n - 1; j++ ) {
if( comparator.compare( array[i], array[j + 1]) > 0 ) {
tempVar = array[j + 1];
array[j + 1] = array[i];
array[i] = tempVar;
}
}
}
}
BubbleSort.sort( students.length, students, new Comparator<Student>() {
public int compare(Stundent lhs, Student rhs ) {
//compare gpa
}
});