Sunday, December 21, 2014

Java: Insertion sort

public class insertSortSolution {

 
 public static void main(String[] args) {
      int temp, j, N;
Scanner sc= new Scanner(System.in);
N=sc.nextInt();
int ar[]= new int[N];
for(int i=0;i<N;i++)
    ar[i]=sc.nextInt();
   
for(int i=1;i<N;i++)
{
temp=ar[i];
j=i-1;
while(j>=0 && ar[j]>temp)
{
ar[j+1]=ar[j];
j=j-1;
}
ar[j+1]=temp;
}
     for(int i=0;i<N;i++)
System.out.println(ar[i]);
   }
}

Input# 1
8 1 2 3 4 3 3 2 1<br /><b style="color: black; font-family: 'Times New Roman'; font-size: medium; line-height: normal; white-space: normal;">Output# 1</b><xmp style="margin-bottom: 0px; margin-top: 0px;">1 1 2 2 3 3 3 4

No comments:

Post a Comment