In Java, you will sort an array of objects - using any of the sort methods or th
ID: 3808335 • Letter: I
Question
In Java, you will sort an array of objects - using any of the sort methods or the Selection sort.
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 Your code should represent your own work and should not be copied from a site. Make sure you write all the methods listed above. THANk YOU
Explanation / Answer
HI, Please find my implementation.
Please let me know in case of any issue.
public class StudentSort {
public static void doSelectionSort(Student[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j].getId() < arr[index].getId())
index = j;
Student smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[]){
Student[] arr = {
new Student(1, "pravesh"),
new Student(4, "Alex"),
new Student(2, "Mukesh"),
new Student(7, "Rahul"),
new Student(10, "Bob"),
new Student(5, "Catrina"),
new Student(4, "Zebta"),
new Student(19, "Lokesh")
};
for(Student i:arr){
System.out.println(i);
}
System.out.println("Befor Sorting");
System.out.println("----------------------------------------------- ");
doSelectionSort(arr);
System.out.println("After Sorting");
for(Student i:arr){
System.out.println(i);
}
}
}
/*
Sample run:
1 pravesh
4 Alex
2 Mukesh
7 Rahul
10 Bob
5 Catrina
4 Zebta
19 Lokesh
Befor Sorting
-----------------------------------------------
After Sorting
1 pravesh
2 Mukesh
4 Alex
4 Zebta
5 Catrina
7 Rahul
10 Bob
19 Lokesh
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.