SORT ARRAY OF OBJECTS – by name – by date

The bubble sort can sort numbers, Strings and arrays of objects. For an animation on how the bubble sort algorithm works click here. You may need to revise how the String method “compareTo” works.

To sort an array of objects alphabetically by name . . .

Example: An array of Dog objects. The Dog class has the following fields ie name, age, and pedigree (String, int, and boolean respectively)

We want to sort the array using the names of the dogs. Below is a method we could call to do this for us. Note that the method is void and therefore there is no return type.

// Sorts alphabetically by the dog’s name.
public void bubbleSortName (){ // We could return the array but here the method is void. 
Dogs temp; // There is a Dog class. Here we create a single temp Dog object to help swap the elements around if needed.

for(int i = 0; i < size – 1; i++){ // The animation referred to above explains the role of each loop.
for (int k = i + 1; k < size; k++) {
String name1 = dogArray[i].getName(); // We get the name of the “first” dog.
String name2 = dogArray[k].getName(); // We get the name of the “second” dog.
int value = name1.compareTo(name2); // “compareTo” returns an int.
if(name1.compareTo(name2) > 0) { // If positive, name1 comes after name2 and therefore we need to swap.
temp = dogArray[i]; // Name1 goes into the temp object.
dogArray[i] = dogArray[k]; // Name2 overwrites name1.
dogArray[k] = temp; // Name1 goes into the position of name2
} // end if
} // end inner loop
} // end outer loop // The return would go here if the method was not void. We would pass the array back.
} // end method
} // end class


To sort an array of objects alphabetically by date

click here