Showing posts with label selection sort in java source code. Show all posts
Showing posts with label selection sort in java source code. Show all posts

Wednesday, June 5, 2013

Exchange Selection Sort in Java

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:


9234781245781605110


7347812459281605110


7107812459281605134


7101278459281605134


7101234459281605178


7101234459281605178


7101234455181609278


7101234455160819278


7101234455160789281


7101234455160788192


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.