**Sorting Algorithm Tutorials - Herong's Tutorial Examples** - Version 6.01, by Dr. Herong Yang

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

- Elements to be sorted are stored from "fromIndex" to "toIndex-1" inclusive.
- At any given time, elements from "fromIndex" to "i-1" are sorted.
- At any given time, elements from "i" to "toIndex-1" are not sorted.
- As shown in the diagram, element at location "i" needs to be inserted at location "j", and all elements from "j" to "i-1" need to be shifted to the right by one location.

*Last update: 2011.*

Table of Contents

Introduction of Sorting Algorithms

Java API for Sorting Algorithms

►Insertion Sort Algorithm and Implementation

Insertion Sort - Algorithm Introduction

►Insertion Sort - Java Implementation

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