Selection Sort
/**
The selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping
it with the item in the next position to be filled. The selection sort has a complexity of O(n2).
It yields a 60% performance improvement over the bubble sort, but the insertion sort is over twice as fast as
the bubble sort and is just as easy to implement as the selection sort. In short, there really isn't any reason
to use the selection sort - use the insertion sort instead.
If you really want to use the selection sort for some reason, try to avoid sorting lists of more than a 1000 items
with it or repetitively sorting lists of more than a couple hundred items.
Pros: Simple and easy to implement.
Cons: Inefficient for large lists, so similar to the more efficient
insertion sort that the insertion sort should be used in its place.
*/
class SelectionSort
{
public static void main(String[] args)
{
int a[]={2,1,4,6,-1};
int j=0,temp=0;
for(int i=0;i<a.length-1;i++)
{
int min=i;
for(j=i+1;j<a.length;j++)
{
if(a[j]<a[min])
min=j;
}
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
The selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping
it with the item in the next position to be filled. The selection sort has a complexity of O(n2).
It yields a 60% performance improvement over the bubble sort, but the insertion sort is over twice as fast as
the bubble sort and is just as easy to implement as the selection sort. In short, there really isn't any reason
to use the selection sort - use the insertion sort instead.
If you really want to use the selection sort for some reason, try to avoid sorting lists of more than a 1000 items
with it or repetitively sorting lists of more than a couple hundred items.
Pros: Simple and easy to implement.
Cons: Inefficient for large lists, so similar to the more efficient
insertion sort that the insertion sort should be used in its place.
*/
class SelectionSort
{
public static void main(String[] args)
{
int a[]={2,1,4,6,-1};
int j=0,temp=0;
for(int i=0;i<a.length-1;i++)
{
int min=i;
for(j=i+1;j<a.length;j++)
{
if(a[j]<a[min])
min=j;
}
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}