Class 12

Insertion Sort in Java

Write a program to allow the user to enter N integers into a one-dimensional array.

Now sort the integers in ascending order using insertion sort technique.

In insertion sort, during each iteration, it picks one element from the list, and places it in its appropriate location where it needs to be after the list is sorted.

This process repeats as long as the entire list of elements are not sorted in the list.

class InsertionSort{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(;
        System.out.print("Number of elements: ");
        int n = Integer.parseInt(br.readLine());
        int a[] = new int[n];
        int i = 0;
        System.out.println("Enter the elements:");
        for(i = 0; i < a.length; i++)
            a[i] = Integer.parseInt(br.readLine());
        i = 1;
        while(i < a.length){ int j = i;
            while(j > 0 && a[j - 1] > a[j]){
                int temp = a[j];
                a[j] = a[j - 1];
                a[j - 1] = temp;
        System.out.println("Sorted list:");
        for(i = 0; i < a.length; i++)
            System.out.print(a[i] + "\t");

By admin

I am a Computer Science teacher in one of the renowned schools in India. I teach Java programming language to my students, and I maintain a website

4 replies on “Insertion Sort in Java”

Sir,a program is given which states that:
WAP in Java to display all the prime fibonacci numbers from m to n.(m=starting number, n=ending number)&(m<n).Both m and n are inclusive.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.