Insertion Sort : Sort « Collections « Java Tutorial






public class MainClass {
  public static void main(String[] args) {
    int[] intArray = new int[] { 2, 6, 3, 8, 4, 9, 1 };

    for (int i : intArray) {
      System.out.print(i);
    }
    System.out.println();
    insertionSort(intArray);

    for (int i : intArray) {
      System.out.print(i);
    }

  }

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

    for (out = 1; out < intArray.length; out++) {
      int temp = intArray[out];
      in = out;
      while (in > 0 && intArray[in - 1] >= temp) {
        intArray[in] = intArray[in - 1];
        --in;
      }
      intArray[in] = temp;
    }
  }

  private static void swap(int[] intArray, int one, int two) {
    int temp = intArray[one];
    intArray[one] = intArray[two];
    intArray[two] = temp;
  }
}
2638491 
1234689








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