Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Thursday 28 December 2017

java program to implement insertion sort

 import java.util.Scanner;

 class insertionsort

{

 public static void main (String[] args)   

{    

Scanner sc=new Scanner(System.in);    

System.out.println("enter size of array");    

int size=sc.nextInt();       

int a[] =new int[size];      

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

for(int i=0;i<size;i++)       

{        

a[i]=sc.nextInt();       

}       

System.out.println("Array after Sorting :");       

for(int i=0;i<a.length;i++)       

{           

int j = i;

while(j>0)           

{               

if(a[j-1] > a[j])               

{                   

int temp = a[j-1];                   

a[j-1] = a[j];                   

a[j] = temp;               

}               

else               

{                   

break;               

}               

j--;           

}       

}

for(int x : a)       

{           

System.out.println(x);       

}
}

}

No comments:

Post a Comment