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.

import java.io.*;
class InsertionSort{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        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;
                j--;
            }
            i++;
        }
        System.out.println("Sorted list:");
        for(i = 0; i < a.length; i++)
            System.out.print(a[i] + "\t");
        System.out.println();
    }
}

4 thoughts on “Insertion Sort in Java

  1. 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