Given a list of Employees ( name and grade). Output the names of the top 2 employees selected for a task(sorted based on grade and then alphabetically).
I am using a maxHeap and override the compareTo method of the Employee class to define the sorting order while initializing the heap .I would like to know if there is a more efficient way(space/time).
The Code:
//Employee class
class Employee implements Comparable<Employee>{
String name;
int grade;
public Employee (String name,int grade){
this.name = name;
this.grade = grade;
}
@Override
public int compareTo(Employee e) {
if(this.grade == e.grade) {
// if the grades are the same then alphabetical priority
return e.name.compareTo(this.name);
}
if(this.grade < e.grade) return -1;
return 1;
}
}
Class to build max heap and print out two names
class EmployeePicker {
public static void main(String[] args) {
PriorityQueue<Employee> employeeHeap = new PriorityQueue<>(5,Collections.reverseOrder());
// add 5 employees
employeeHeap.add(new Employee("Adam", 5));
employeeHeap.add(new Employee("Annie",7));
employeeHeap.add(new Employee("Amit", 5));
employeeHeap.add(new Employee("Carl", 5));
employeeHeap.add(new Employee("Tom", 4));
// print first two names
System.out.println(employeeHeap.poll().name);
System.out.println(employeeHeap.poll().name);
}
}