Insert Sort for objects

 
public class ObjectInsertSort {
  private Person[] a;

  private int nElems;

  public ObjectInsertSort(int max) {
    a = new Person[max];
    nElems = 0;
  }

  // put person into array
  public void insert(String last, String first, int age) {
    a[nElems] = new Person(last, first, age);
    nElems++;
  }

  public void display() {
    for (int j = 0; j < nElems; j++)
      a[j].displayPerson();
  }

  public void insertionSort() {
    int in, out;

    for (out = 1; out < nElems; out++) {
      Person temp = a[out]; // out is dividing line
      in = out; // start shifting at out

      while (in > 0 && // until smaller one found,
          a[in - 1].getLast().compareTo(temp.getLast()) > 0) {
        a[in] = a[in - 1]; // shift item to the right
        --in; // go left one position
      }
      a[in] = temp; // insert marked item
    }
  }

  public static void main(String[] args) {
    int maxSize = 100; // array size
    ObjectInsertSort arr;
    arr = new ObjectInsertSort(maxSize); // create the array

    arr.insert("Jo", "Yin", 24);
    arr.insert("Pengzhou", "Yin", 59);
    arr.insert("James", "Chen", 37);
    arr.insert("Chirs", "Paul", 37);
    arr.insert("Rob", "Tom", 43);
    arr.insert("Carlo", "Sato", 21);
    arr.insert("Al", "Henry", 29);
    arr.insert("Nancy", "Jose", 72);
    arr.insert("Vang", "Minh", 22);

    System.out.println("Before sorting:");
    arr.display(); // display items

    arr.insertionSort(); // insertion-sort them

    System.out.println("After sorting:");
    arr.display(); // display them again
  }
}

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 void displayPerson() {
    System.out.print("   Last name: " + lastName);
    System.out.print(", First name: " + firstName);
    System.out.println(", Age: " + age);
  }

  public String getLast() {
    return lastName;
  }
}
  
Home 
  Java Book 
    Runnable examples  

Algorithm:
  1. Binary search
  2. Binary Search Insert
  3. Recursive Binary Search Implementation in Java
  4. Linear Searching double Arrays
  5. Bubble sort
  6. Heap sort
  7. Merge sort
  8. Fast Merge Sort
  9. Fast Quick Sort
  10. Simple version of quick sort
  11. Quicksort for sorting arrays
  12. Quick Sort Implementation with median-of-three partitioning and cutoff for small arrays
  13. Quick sort with median-of-three partitioning
  14. Insert sort
  15. Insert Sort for objects
  16. Selection sort
  17. Shell sort
  18. Fibonacci
  19. Hanoi puzzle
  20. Table of fahrenheit and celsius temperatures
  21. Growable integer array
  22. Linked List class
  23. Binary Tree
  24. Tree with generic user object