In Selection Sort algorithm, we keep on selecting the smallest element (while sorting in ascending order), and place it in its proper position in the list. This process is repeated until the entire list is sorted.
Below is the code written in Java that applies exchange selection sort technique to sort an array of integer elements:
class SelectionSort{
public static void main(String args[]){
int a[]={92, 34, 78, 12, 45, 7, 81, 60, 51, 10};
int i, j, temp, pos, small;
for(i=0;i<a.length;i++){
small=a[i];
pos=i;
for(j=i+1;j<a.length;j++){
if(a[j]<small){
small=a[j];
pos=j;
}
}
temp=a[i];
a[i]=small;
a[pos]=temp;
}
for(i=0;i<a.length;i++)
System.out.print(a[i]+"\t");
System.out.println();
}
}
Below is the sequence that demonstrates how the elements are sorted in ascending order, in Exchange Selection Sort:
The elements colored green indicates sorted elements. The elements in red are the ones that are compared with each other to see if they need to be swapped.