I have a Students list that I would want to sort using Selection Sort algorithm. I want to sort Students list based on first name, age and id. My student class is a POJO class just with getters and setters. It has 4 instance variables- firstName, lastName, age and id.
My code below-
private static void selectionSort(Student[] list, String key) {
for (int i = 0; i< list.length - 1; i++) {
int min_index = i;
for (int j = i+1; j < list.length; j++) {
// TO-DO for each of the unsorted elements
// if element < currentMinimum
if (list[j].compareTo(list[min_index])) {
// TO-DO
}
}
}
}
Here, list parameter is the list of Student objects. I am passing key parameter here which would be either first name or id or age.
I have written my swap method as below-
private static void swap(Students[] list, int index1, int index2) {
Student temp = list[index1];
list[index1] = list[index2];
list[index2] = temp;
}
I am calling my method like this-
selectionSort(list, "firstName");
selectionSort(list, "id");
selectionSort(list, "age");
I am not sure how to compare the value in nested loop for each of the unsorted elements. I tried using compareTo but it gives me error. I am trying to implement this without using compareTo().