Insertion Sort - Java Implementation

This section provides a tutorial on how to implement the Insertion Sort algorithm in Java. An implementation diagram is also provided.

Here is my Java implementation of Insertion Sort algorithm:

/**
 * HyArrays.java
 * This class contains sorting methods similar to java.util.Arrays.
 * All sorting methods should have a signature of 
 * %Sort(Object[] a, int fromIndex, int toIndex)
 * where "fromIndex" is inclusive, and "toIndex" is exclusive.
 * Copyright (c) 2011 by Dr. Herong Yang, herongyang.com
 */
public class HyArrays {
   public static void insertionSort(Object[] a, int fromIndex, 
      int toIndex) {
      Object d;
      for (int i=fromIndex+1; i<toIndex; i++) {
         d = a[i];
         int j = i;
         while (j>fromIndex && ((Comparable)a[j-1]).compareTo(d)>0) {
            a[j] = a[j-1];
            j--;
         }
         a[j] = d;
      }   
   }
}

The following diagram illustrates how this implementation works:

                             ----------24   4  53   ...            42
                            |               |   |                   |
        +-----------+---+---+---+---+---+---+---+-------------------+
        |           |   |    /   /   /                              
        5   ...    17  20  29  36  39                               
        |           |   |   |           |                           |
fromIndex             j-1   j           i                   toIndex-1

Last update: 2011.

Table of Contents

 About This Book

 Introduction of Sorting Algorithms

 Java API for Sorting Algorithms

Insertion Sort Algorithm and Implementation

 Insertion Sort - Algorithm Introduction

Insertion Sort - Java Implementation

 Insertion Sort - Performance

 Insertion Sort - Implementation Improvements

 Selection Sort Algorithm and Implementation

 Bubble Sort Algorithm and Implementation

 Quicksort Algorithm and Implementation

 Merge Sort Algorithm and Implementation

 Heap Sort Algorithm and Implementation

 Shell Sort Algorithm and Implementation

 Performance Summary of Java Implementations

 References

 PDF Printing Version