Insertion sort in Java

Here is a sample code for inserstion sort.

The basic approach is to keep a pivot up to which the list is sorted.

Insert the value (initially at the pivot) at the right place in the already sorted array to the left of the pivot.

import java.util.*;

public class InsertionSort {

     public static void main(String []args){
         int a[] = {123, 112, 134, 97, 34};
         sort(a);
        System.out.println("sorted :" + Arrays.toString(a));
     }
     
     public static void sort(int[] a) {
         if (a.length <= 1) {
             return;
         }
         int pivotValue;
         int j;
         for (int i = 1; i < a.length; i++) {
             pivotValue = a[i];
             for (j = i-1; j >= 0; j--) {
                 if (a[j] > pivotValue) {
                     a[j + 1] = a[j];
                 } else {
                     break;
                 }
             }
             a[j+1] = pivotValue;
             System.out.println("pivot :" + i + " : " + Arrays.toString(a));
         }
     }
}

Kj
Kj [/.] Sreekumar programs computers as a hobby and profession. Into programming from his school days, Sree uses Codemarvels to key in facts and fixes he finds interesting while working on different projects. Some of the articles here give away a few shades of his philosophical leanings too.

Leave a Comment

Your email address will not be published. Required fields are marked *