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 (selection 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);
I have written the required method along with class definition
Student.java
class Student { String firstName, lastName; double gpa; public Student(String fn, String ln, double g) { this.firstName = fn; this.lastName = ln; this.gpa = g; } /** * function to sort the student by the last name * @param students */ public static void sortByLastName(Student[] students) { for (int i = 0; i < students.length; i++) { // index for selecting entity int index = i; for (int j = i + 1; j < students.length; j++) { // comparing based on last name if (students[j].lastName.compareTo(students[index].lastName) < 1) { index = j; } } // swapping the values Student temp = students[index]; students[index] = students[i]; students[i] = temp; } } @Override public String toString() { return String.format("%s, %s, %.2f\n", this.firstName, this.lastName, this.gpa); } public static void main(String[] args) { Student[] students = new Student[8]; students[0] = new Student("Saoud", "Mohamed", 3.61); students[1] = new Student("Abdelkader", "Farouk", 2.83); students[2] = new Student("Beshr", "Alsharqawy", 1.99); students[3] = new Student("Nader", "Salah", 3.02); students[4] = new Student("Basem", "Hawary", 2.65); students[5] = new Student("Abdullah", "Babaker", 2.88); students[6] = new Student("Abdelaal", "Khairy", 3.13); students[7] = new Student("Mohamedain", "Marsily", 4.00); // calling method for sorting the students sortByLastName(students); // printing the students for (Student s : students) { System.out.println(s); } } }
// OUT
Please do let me know if u have any concern...
Get Answers For Free
Most questions answered within 1 hours.