INSERTION SORT PROGRAM IN JAVA

 /*  
 Arraging set of elements in increment order using   
 Insertion Sort in java;   
 */  
 import java.util.*;   
 class InsertionSort  
 {  
      static Scanner in = new Scanner(System.in);   
      public static void main(String[]args)  
           {  
           System.out.println("Enter your Array Size");  
           int n = in.nextInt();   
           int[]arr = new int[n];   
           fillArray(arr,n);   
           insertionSort(arr,n);// callint selection sort method  
           printArray(arr,n);   
           }  
 // Insertion sort method   
      static void insertionSort(int[]a,int n)  
           {  
           for(int out=1;out<n;out++)                 
                {  
                int temp = a[out]; // 2 1 5 3 0   
                int in = out;   
                while(in>0&&a[in-1]>=temp)  
                     {  
                          a[in]=a[in-1];  
                          in--;   
                     }  
                a[in]=temp;                                           
                }  
           }  
      static void fillArray(int []a, int n)// fill array Method  
           {  
                System.out.println("Enter Your Elements");  
                for(int i=0;i<n;i++)  
                     a[i]=in.nextInt();   
           }  
      static void printArray(int []a, int n)// print array Method.  
           {  
                System.out.print("Array Elements = ");  
                for(int i=0;i<n;i++)  
                     System.out.print(a[i]+"\t");  
                System.out.println(" ");  
           }  
 }  

Post a Comment

3 Comments