Tuesday, 21 August 2012

To implement selection sort technique


import java.util.*;
public class Selection
{

static void selectionsort(int a[])
{
int p,min,t;
for(int i=0;i<=a.length-2;i++)
{
min=a[i];p=i;
for(int j=i+1;j<=a.length-1;j++)
if(a[j]<min)
{
min=a[j];
p=j;
}
t=a[i];
a[i]=a[p];
a[p]=t;
}
}
public static void main(String args[])
{
System.out.println("Enter number of elements");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter element"+(i+1));
a[i]=s.nextInt();
}
selectionsort(a);
for(int i=0;i<=n-1;i++)
System.out.println(a[i]);
}//end of main

}//end of selection


OUTPUT
==========================================================

C:\Program Files\Java\jdk1.7.0_02\bin>javac Selection.java

C:\Program Files\Java\jdk1.7.0_02\bin>java Selection
Enter number of elements
5
Enter element1
987
Enter element2
5454
Enter element3
534
Enter element4
65
Enter element5
154

65
154
534
987
5454

No comments:

Post a Comment