In: Computer Science
Write a Java program that sorts an array of “Student” in an aescending order of their “last names”. The program should be able to apply (Insertion sort):
Student [] studs = new Student[8];
s[0] = new Student("Saoud", "Mohamed", 3.61);
s[1] = new Student("Abdelkader", "Farouk", 2.83);
s[2] = new Student("Beshr" , "Alsharqawy", 1.99);
s[3] = new Student("Nader", "Salah", 3.02);
s[4] = new Student("Basem", "Hawary", 2.65);
s[5] = new Student("Abdullah", "Babaker", 2.88);
s[6] = new Student("Abdelaal", "Khairy", 3.13);
s[7] = new Student("Mohamedain", "Marsily", 4.00);

public class StudentSorter {
static class Student {
private String first, last;
private double gpa;
public Student(String first, String last, double gpa) {
this.first = first;
this.last = last;
this.gpa = gpa;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
public double getGpa() {
return gpa;
}
@Override
public String toString() {
return first + " " + last + ": " + gpa;
}
}
public static void sortStudents(Student arr[]) {
for (int i = 1; i < arr.length; i++) {
Student key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j].getLast().compareTo(key.getLast()) > 0) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
public static void main(String[] args) {
Student[] s = new Student[8];
s[0] = new Student("Saoud", "Mohamed", 3.61);
s[1] = new Student("Abdelkader", "Farouk", 2.83);
s[2] = new Student("Beshr", "Alsharqawy", 1.99);
s[3] = new Student("Nader", "Salah", 3.02);
s[4] = new Student("Basem", "Hawary", 2.65);
s[5] = new Student("Abdullah", "Babaker", 2.88);
s[6] = new Student("Abdelaal", "Khairy", 3.13);
s[7] = new Student("Mohamedain", "Marsily", 4.00);
sortStudents(s);
for(Student x: s) {
System.out.println(x);
}
}
}
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.