Insertion sort

 

// 3. Insertion sort

import java.io.*;

import java.util.*;

 

class InsertionSort

{

     public static void main(String [] as) throws IOException

     {

          Scanner sc = new Scanner(System.in);

          int i, j, arrlen, tmp;

         

          System.out.print("Enter array length : ");

          arrlen = sc.nextInt();

         

          System.out.println("Enter array elements : ");

          int arr[] = new int[arrlen];

          for(i=0;i<arrlen;i++)

              arr[i]=sc.nextInt();

         

          // Sorting

          for(i=1;i<arrlen;i++)

          {

              tmp = arr[i];

              for(j=i;j>0;j--)

              {

                   if(tmp>arr[j-1])

                        break;

             

                   arr[j] = arr[j-1];

              }

              arr[j] = tmp;

          }

             

          System.out.print("Sorted array : ");

          for(i=0;i<arrlen;i++)

              System.out.print(arr[i]+"  ");

         

     }

}


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu