Apply Insertion Sort on Data and Arrange in Ascending order and Descending order.
Program:
import java.util.Scanner;
class insertion{
public static void main(String arg[]){
Scanner sc=new Scanner(System.in);
int i;
int a[]=new int[5];
System.out.println("Enter numbers is array:");
for(i=0;i<5;i++)
{
a[i]=sc.nextInt();
}
insertion_ace(a);
insertion_dec(a);
}
static void insertion_ace(int a[])
{
int i,j,tmp,min;
for(i=1;i<5;i++)
{
tmp=a[i];
j=i-1;
while(j>=0 && a[j]<tmp)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=tmp;
}
System.out.println("Accending order:");
for(i=0;i<5;i++)
System.out.println(a[i]);
}
static void insertion_dec(int a[])
{
int i,j,tmp,min;
for(i=1;i<5;i++)
{
tmp=a[i];
j=i-1;
while(j>=0 && a[j]>tmp)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=tmp;
}
System.out.println("Accending order:");
for(i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
public static void main(String arg[]){
Scanner sc=new Scanner(System.in);
int i;
int a[]=new int[5];
System.out.println("Enter numbers is array:");
for(i=0;i<5;i++)
{
a[i]=sc.nextInt();
}
insertion_ace(a);
insertion_dec(a);
}
static void insertion_ace(int a[])
{
int i,j,tmp,min;
for(i=1;i<5;i++)
{
tmp=a[i];
j=i-1;
while(j>=0 && a[j]<tmp)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=tmp;
}
System.out.println("Accending order:");
for(i=0;i<5;i++)
System.out.println(a[i]);
}
static void insertion_dec(int a[])
{
int i,j,tmp,min;
for(i=1;i<5;i++)
{
tmp=a[i];
j=i-1;
while(j>=0 && a[j]>tmp)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=tmp;
}
System.out.println("Accending order:");
for(i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
No comments:
Post a Comment