Saturday, 30 July 2016

Selection sort

selection sort
import java.io.*;
class Selectionsort
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=0,i,j,t;
int a[]=new int[10];
System.out.println("Enter size of the array:");
try
{
n=Integer.parseInt(br.readLine());
}
catch(Exception e){}
System.out.println("Enter elements into the array:");
try
{
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
}
catch(Exception e){}
i=0;
while(i<n-1)
{
int key=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[key])
{
key=j;
}
}
t=a[key];
a[key]=a[i];
a[i]=t;
i++;
}
System.out.println("The sorted array is:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}


Output:
javac Selectionsort.java
java Selectionsort
Enter the size of array
5
Enter the elements into the array
45
34
76
12
69
The sorted array is
76 69 45 34 12