DEV Community

jiangtao zhu
jiangtao zhu

Posted on

Insertion Sorting of Data Structures and Algorithms

Insertion sorting, also known as direct insertion sorting, is an effective algorithm for sorting a small number of elements. Insertion sorting is a simple sorting method, whose basic idea is to insert a record into an ordered table that has already been sorted, in order to obtain a new ordered table with an increase of 1 record count.
The following is the JAVA code for inserting and sorting array a, which is sorted in ascending order.

public class Insertion
{
public static void sort(Comparable[] a)
{
//Arrange a [] in ascending order
int N=a.length;
for (int i=1;i {
//Insert a [i] into a [i-1], a [i-2], a [i-3]
for(int j=i;j>0&&(a[j].compareTo(a[j-1])<0);j--)
{
Comparable temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
}

Top comments (0)