Please write in java only Sort an array of objects using an
Please write in java only
Sort an array of objects - using any of the sort methods or the Selection sort. It\'s your choice. Use the following criteria for your assignment:
The object class should be a Student with the following attributes:
id: integer
name: String
write the accessors, mutators, constructor, and toString().
In your main test class you will write your main method and do the following things:
Create an array of Student objects with at least 5 students in your array.
The sort method must be written yourself and included in the main class. The sort
method will sort based on student id.
Output the array out in unsorted order as it exists.
Sort the array
Output the sorted array
Solution
// Student.java
public class Student
{
int id;
String name;
public Student()
{
this.id = 1;
this.name = \"None\";
}
public Student(int id, String name)
{
this.id = id;
this.name = name;
}
public void setName(String name)
{
this.name =name;
}
public void setID(int id)
{
this.id =id;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public static void studentSort(Student[] student, int size )
{
for (int i= 0; i < size ;i++ )
{
for (int j= 0; j < size ;j++ )
{
if(student[i].getId() < student[j].getId())
{
String temp1 = student[i].getName();
String temp2 = student[j].getName();
student[i].setName(temp2);
student[j].setName(temp1);
int t1 = student[i].getId();
int t2 = student[j].getId();
student[i].setID(t2);
student[j].setID(t1);
}
}
}
}
@Override
public String toString()
{
return String.format(\"ID: \" + id + \"\\t\" + \"Name: \" + name);
}
public static void main(String[] args)
{
int size = 5;
Student[] student = new Student[size];
for( int i=0; i<5; i++ )
student[i] = new Student();
student[0].setName(\"Ayush\");
student[0].setID(34);
student[1].setName(\"Alex\");
student[1].setID(23);
student[2].setName(\"Michael\");
student[2].setID(43);
student[3].setName(\"Jason\");
student[3].setID(67);
student[4].setName(\"Eoin\");
student[4].setID(11);
System.out.println(\"\ UnSorted:\");
for (int i= 0; i < 5 ;i++ )
{
System.out.println(student[i].toString());
}
Student.studentSort(student,size);
System.out.println(\"\ Sorted:\");
for (int i= 0; i < 5 ;i++ )
{
System.out.println(student[i].toString());
}
}
}
/*
output:
UnSorted:
ID: 34 Name: Ayush
ID: 23 Name: Alex
ID: 43 Name: Michael
ID: 67 Name: Jason
ID: 11 Name: Eoin
Sorted:
ID: 11 Name: Eoin
ID: 23 Name: Alex
ID: 34 Name: Ayush
ID: 43 Name: Michael
ID: 67 Name: Jason
*/


