Apply Selection Sort on Data and Arrange in Ascending order and Descending order.
Program:
import java.util.Scanner;
class selection{
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();
}
selection_ace(a);
selection_dec(a);
}
static void selection_ace(int a[])
{
int i,j,tmp,min;
for(i=0;i<5;i++)
{
min=i;
for(j=i+1;j<5;j++)
{
if(a[j]<a[min])
{
min=j;
}
}
if(min!=i)
{
tmp=a[min];
a[min]=a[i];
a[i]=tmp;
}
}
System.out.println("Acending order:");
for(i=0;i<5;i++)
System.out.println(a[i]);
}
static void selection_dec(int a[])
{
int i,j,tmp,min;
for(i=0;i<5;i++)
{
min=i;
for(j=i+1;j<5;j++)
{
if(a[j]>a[min])
{
min=j;
}
}
if(min!=i)
{
tmp=a[min];
a[min]=a[i];
a[i]=tmp;
}
}
System.out.println("Decending order:");
for(i=0;i<5;i++)
System.out.println(a[i]);
}
}
No comments:
Post a Comment