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));
}
}
}

Sreekumar (KJ) has been a hobby programmer from school days. Codemarvels is his personal blog from the year 2010, where he writes about technology, philosophy, society and a bit about physics.
He now runs a conversational AI company – DheeYantra – focusing his efforts to help businesses improve operational efficiency using digital employees powered by AI.