This site requires JavaScript, please enable it in your browser!
Greenfoot back
JasonZhu
JasonZhu wrote ...

2014/3/24

Sorting a list of Employee names

JasonZhu JasonZhu

2014/3/24

#
I have a class hierarchy of public class Person
    public String getWholeName()
    {
        return lastName + ", " + firstName;
    }
public abstract class Employee extends Person implements Comparable public class Company
    private ArrayList<Employee>employees;

    public Company()
    {
        employees = new ArrayList<Employee>();
    }
I was given the assignment of writing a selection and insertion sort for the Employees whole names. I was told to implement the Comparable interface. With only this info I am unsure of how to go about this. Do I write a compareTo method in the Employee class and use it in my sorting algorithms? I am confused. I appreciate any help. I have the following sorts already:
public static void selectionSort1(int[] x) {
    for (int i=0; i<x.length-1; i++) {
        for (int j=i+1; j<x.length; j++) {
            if (x[i] > x[j]) {
                //... Exchange elements
                int temp = x[i];
                x[i] = x[j];
                x[j] = temp;
            }
        }
    }
}
 public static void insertionSort(int toSort[]) {  
  for (int i = 0; i < toSort.length; i++) {  
   int value = toSort[i];  
   int j = i - 1;  
   while (j >= 0 && toSort[j] > value) {  
    toSort[j + 1] = toSort[j];  
    j = j - 1;  
   }  
   toSort[j + 1] = value;  
  
  }  
 }  
I understand that I would have to modify my sorts according to the output of the compareTo method. I understand it returns 0, a positive number, or a negative number.
danpost danpost

2014/3/25

#
Please refer to the page on Object Ordering in the Java tutorials.
JasonZhu JasonZhu

2014/3/25

#
Thanks for the sharing of the site. I got it working :).
You need to login to post a reply.