Insert sort

 
public class Main {
  public static void main(String[] args) {
    int maxSize = 100; // array size
    InsertSort arr; // reference to array
    arr = new InsertSort(maxSize); // create the array

    arr.insert(47);
    arr.insert(99);
    arr.insert(44);
    arr.insert(35);
    arr.insert(22);
    arr.insert(88);
    arr.insert(41);
    arr.insert(00);
    arr.insert(16);
    arr.insert(33);

    arr.display();

    arr.insertionSort();

    arr.display();
  }

}

class InsertSort {
  private long[] number;

  private int nElems;

  public InsertSort(int max) {
    number = new long[max];
    nElems = 0;
  }

  public void insert(long value) {
    number[nElems] = value;
    nElems++;
  }

  public void display() {
    for (int j = 0; j < nElems; j++)
      System.out.print(number[j] + " ");
    System.out.println("");
  }

  public void insertionSort() {
    int in, out;
    // out is dividing line
    for (out = 1; out < nElems; out++) {
      long temp = number[out]; // remove marked item
      in = out; // start shifts at out
      while (in > 0 && number[in - 1] >= temp) // until one is smaller,
      {
        number[in] = number[in - 1]; // shift item to right
        --in; // go left one position
      }
      number[in] = temp; // insert marked item
    }
  }

}
  

Output:


47 99 44 35 22 88 41 0 16 33 
0 16 22 33 35 41 44 47 88 99
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