Hi, I had an assignment where we had to fox a program and get it working correctly. I fixed 99% of the problems and the program runs correct. The only thing that is wrong is my insertionSort() method. It runs correctly, but in the wrong order.
Currently its listing names in descending order, comparing the last names (if last names are equal then compares first names). I have been messing around with my loops for a while now and cant figure out how to switch the order which it runs the sort. The fix is probably something really small and obvious that I'm missing.
public static void insertionSort(Person[] personArray) {
int i, j;
for (j = 1; j < personArray.length; j++) {
Person temp = personArray[j];
i = j;
while (j > 0 && personArray[j - 1].compare(temp) < 0 ) {
personArray[j] = personArray[j - 1];
j--;
}
personArray[j] = temp;
}
}
public static void main(String[] args) {
System.out.println("Hello and Good Luck with your Debugging Exercise");
// initialize an array of comparable objects
Person[] array = new Person[5];
array[0] = new Person("Edison", "Zach");
array[1] = new Person("Clarkson", "Happy");
array[2] = new Person("Edison", "Thomas");
array[3] = new Person("John", "Doe");
array[4] = new Person("Allen", "Woody");
Lab6.insertionSort(array);
for (Person p : array) {
System.out.println(p);
}
}
}
Output from this code is currently:
- Doe John
- Zach Edison
- Thomas Edison
- Happy Clarkson
- Woody Allen
Should be:
- Woody Allen
- Happy Clarkson
- Thomas Edison
- Zach Edison
- John Doe