Insertion Sort Program in Java

Insertion sort is easy and simple algorithm that generate the final sorted array (or list) one item at a time. The array is looked successively and unsorted things are moved and embedded into the arranged sub-list . This algorithm is not suitable for large data sets than more advaned algo’s like quick and heap sorting alogorithms.

There are two .java classes for the Insertion sorting algorithm:

  1. Runner class.
  2. Sort Class.

Code is successfully compiled on the Eclipse compiler

Runner Class:

package insertion_sort;

public class Runner {

public static void main(String[] args) {
int maxSize = 100;
Sort sort = new Sort(maxSize);
sort.insert(77);
sort.insert(99);
sort.insert(44);
sort.insert(55);
sort.insert(22);
sort.insert(88);
sort.insert(11);
sort.insert(00);
sort.insert(66);
sort.insert(33);

// sort.display();
sort.Insertion_Sort();

sort.display();
}

}

Sort Class:

package insertion_sort;

public class Sort {

private long[] a;
private int nElems;

public Sort(int max)
{
a = new long[max];
nElems = 0;
}
public void insert(long value)
{
a[nElems] = value;
nElems++;
}
public void display()
{
for(int i=0; i<nElems; i++)
{
System.out.print(a[i] + ” “);
}
System.out.println();
}
public void Insertion_Sort()
{
int in, out;
for(out = 1; out<nElems; out++)
{
long temp = a[out];
in = out;

while(in>0 && a[in-1] >= temp)
{
a[in] = a[in-1];
–in;
}
a[in] = temp;
for(int i=0; i<nElems; i++)
{
System.out.print(a[i]+”.”);
}

System.out.println();
}
}
}

Comment if you have any confusion or query thanks !!!

One Comment

Add a Comment

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