Sorting Objects using insertion sort : Sort « Collections « Java Tutorial






class Person {
  private String lastName;

  private String firstName;

  private int age;

  public Person(String last, String first, int a) {
    lastName = last;
    firstName = first;
    age = a;
  }

  public String toString() {
    return "Last name: " + lastName + " First name: " + firstName + " Age: " + age;
  }

  public String getLast() {
    return lastName;
  }
}

public class MainClass {
  public static void main(String[] args) {
    Person[] persons = new Person[] { 
        new Person("a", "b", 23), 
        new Person("i", "a", 25),
        new Person("y", "h", 26), 
        new Person("d", "e", 27) };

    System.out.println("Before sorting:");
    for (Person p : persons) {
      System.out.println(p);
    }
    insertionSort(persons);

    System.out.println("After sorting:");
    for (Person p : persons) {
      System.out.println(p);
    }
  }

  public static void insertionSort(Person[] persons) {
    int in, out;

    for (out = 1; out < persons.length; out++) {
      Person temp = persons[out];
      in = out;

      while (in > 0 && persons[in - 1].getLast().compareTo(temp.getLast()) > 0) {
        persons[in] = persons[in - 1];
        --in;
      }
      persons[in] = temp;
    }
  }
}
Last name: y First name: h Age: 26
Last name: d First name: e Age: 27
After sorting:
Last name: a First name: b Age: 23
Last name: d First name: e Age: 27
Last name: i First name: a Age: 25
Last name: y First name: h Age: 26








9.53.Sort
9.53.1.Bubble Sort
9.53.2.Selection Sort
9.53.3.Insertion Sort
9.53.4.Sorting Objects using insertion sort
9.53.5.Mergesort: merging two arrays into a third
9.53.6.Generic Merge Sorter with generic Comparator
9.53.7.Shellsort
9.53.8.Quicksort: simple version of quick sort
9.53.9.Quick sort with median-of-three partitioning
9.53.10.Quick sort: uses an insertion sort to handle subarrays of fewer than 10 cells