← All resources

Write a program to input an array of size 'N' and sort it using Insertion sort technique.

<h3>Output</h3>
Enter the size:
7
Enter the elements:
32
12
554
23
25
16
76
Printing the elements:
12
16
23
25
32
76
554
import java.io.*;
public class insertion_sort
{
    static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    public static void main()throws IOException
    {
          int i, j, newValue, arr[], n;
          System.out.println("Enter the size:");
          n = Integer.parseInt(br.readLine());
          arr = new int[n];
          System.out.println("Enter the elements:");
          for(i=0;i < n;i++)
          {
              arr[i] = Integer.parseInt(br.readLine());
          }
          for (i = 1; i < n; i++)
          {
             newValue = arr[i];
             j = i;
             while (j > 0 && arr[j - 1] > newValue)
             {
                 arr[j] = arr[j - 1];
                 j--;
             }
             arr[j] = newValue;
          }
          System.out.println("Printing the elements:");
          for(i=0;i < n;i++)
          {
              System.out.println(arr[i]);
          }
    }
}