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 (bubble 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);
Code:
class Student//student class
{
String firstname, lastname;double gpa;
public Student(String firstname, String lastname,
double gpa)//constructor
{
this.firstname =
firstname;this.lastname = lastname;this.gpa = gpa;
}
public String getFirstName()//getter methods
{
return firstname;
}
public String getLastName()
{
return lastname;
}
public double getGPA()
{
return gpa;
}
public void setFirstName(String firstname)//setter
methods
{
this.firstname = firstname;
}
public void setLastName(String lastname)
{
this.lastname = lastname;
}
public void setGPA(double gpa)
{
this.gpa = gpa;
}
}
public class A
{
public static void main(String args[])
{
Student []studs = new
Student[8];int i, j, n=8;//n holds no of objects
studs[0] = new Student("Saoud",
"Mohamed", 3.61);//creating objects
studs[1] = new
Student("Abdelkader", "Farouk", 2.83);
studs[2] = new Student("Beshr" ,
"Alsharqawy", 1.99);
studs[3] = new Student("Nader",
"Salah", 3.02);
studs[4] = new Student("Basem",
"Hawary", 2.65);
studs[5] = new Student("Abdullah",
"Babaker", 2.88);
studs[6] = new Student("Abdelaal",
"Khairy", 3.13);
studs[7] = new
Student("Mohamedain", "Marsily", 4.00);
for(i=0;i<n-1;i++)//bubble
sort
{
for(j=0;j<n-i-1;j++)
{
if((studs[j].getLastName()).compareTo(studs[j+1].getLastName())
> 0)
{
String f =
studs[j].getFirstName();//swap object studs[j]'s contents with that
of object studs[j+1]
String l =
studs[j].getLastName();
double g =
studs[j].getGPA();
studs[j].setFirstName(studs[j+1].getFirstName());
studs[j].setLastName(studs[j+1].getLastName());
studs[j].setGPA(studs[j+1].getGPA());
studs[j+1].setFirstName(f);
studs[j+1].setLastName(l);
studs[j+1].setGPA(g);
}
}
}
System.out.println("After
sorting:");
for(i=0;i<n;i++)
{
System.out.println(studs[i].getFirstName() + " " +
studs[i].getLastName() + " " + studs[i].getGPA());
}
}
}
Output:
Get Answers For Free
Most questions answered within 1 hours.