Insertion Sort - Coder's point

Saturday, March 16, 2019

Insertion Sort

 import java.util.*;  
 public class insertion_sort   
 {   
    void Sort(int array[])   
   {   
     int n = array.length;   
     for (int j = 1; j < n; j++) {   
       int a = array[j];   
       int i = j-1;   
       while ( (i > -1) && ( array [i] > a ) ) {   
         array [i+1] = array [i];   
         i--;   
       }   
       array[i+1] = a;   
     }   
   }   
   public static void main()  
   {    
     insertion_sort ob = new insertion_sort();  
     Scanner in= new Scanner(System.in);  
     System.out.println("Enter the size of array");  
     int n=in.nextInt();  
     int array[]=new int[n];  
      System.out.println("Enter the elements in array");  
     for(int i=0;i<array.length;i++)  
     {  
       array[i]=in.nextInt();  
     }  
     System.out.println("Before Insertion Sort");    
     for(int i:array){    
       System.out.print(i+" ");    
     }    
     System.out.println();    
     ob.Sort(array);//sorting array using insertion sort    
     System.out.println("After Insertion Sort");    
     for(int i:array){    
       System.out.print(i+" ");    
     }    
   }    
 }    
OUTPUT:
Enter the size of array
5
Enter the elements in array
10
12
8
34
6
Before Insertion Sort
10 12 8 34 6 
After Insertion Sort
6 8 10 12 34 

No comments:

Post a Comment