sort objects

Sort objects in Java using Insertion Sort

In our Java program below we use insertion sort to sort Student objects based on the lastName key values.

The doInsertionSort() method in this example is similar to doInsertionSort() method in the insertion sort example, but the only difference is we are comparing the lastName key values instead of a primitive type and we use compareTo() method of the String class for comparisons.

1. Sort objects using insertion sort

In our previous article we had learnt about insertion sort. At each iteration, insertion sort removes one element from the input array and insert that element in a location it belongs within the sorted list. And this is repeated until there are no elements remaining in the input array.

Output

2. Sort objects using Comparator

Output

3. Sort objects using Comparable

Output

References

  1. Wikipedia sorting algorithm
  2. Comparator Oracle Documentation
  3. Comparable Oracle Documentation

Leave a Reply

avatar
  Subscribe  
Notify of