How to implement Selection Sort in a Java Program?

public class SelectionSort
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int a[]={5,4,3,2,1,0,-1,2};
for(int i=0;i<=a.length-2;i++)
{
int min=a[i];
int pos=i;
for(int j=i+1;j<=a.length-1;j++)
{
if(a[j]<min)
{
min=a[j];
pos=j;
}
}
int t=a[i];
a[i]=a[pos];
a[pos]=t;
}for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}

Output

-1
0
1
2
2
3
4
5

 

 

 

 

Leave a Reply