Ad

Friday 3 April 2015

How to implement selection sort algorithm in java

In this post we will see how to implement the selection sort algorithm in java with a sample program.In selection sorting
  1. We will find the smallest element in the array  and  then swap this element with the  element in the 0th index of the  array.
  2. Then we will find the second smallest element in the array and  swap this element with the element in the 1st index of the array.This iteration will continue upto the number of times equal to the the size of the array.
Below sample program will explain this in detail.

package test;

public class SelectionSortSample {

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arry = new int[] { 20, 3, 150, 5, 6, 78, 2, 123, 43, 45, 99, 1,
12 };
SelectionSortSample selectionSort = new SelectionSortSample();
selectionSort.sort(arry);
}

public void sort(int[] arry) {
printElements(arry);
int len = arry.length;
int min = 0;
int temp=0;
for (int i = 0; i < len; i++) {
min=i;
for(int j=i+1;j<len;j++)
{
if(arry[j]<arry[min])
{
min=j;
}
}
temp=arry[i];
arry[i]=arry[min];
arry[min]=temp;
printElements(arry);
}

}

public void printElements(int[] arry) {
for (int i = 0; i < arry.length; i++) {
System.out.print("  " + arry[i]);
}
System.out.println();
}

}


When we run the above program,we will get this output

  20  3  150  5  6  78  2  123  43  45  99  1  12
  1  3  150  5  6  78  2  123  43  45  99  20  12
  1  2  150  5  6  78  3  123  43  45  99  20  12
  1  2  3  5  6  78  150  123  43  45  99  20  12
  1  2  3  5  6  78  150  123  43  45  99  20  12
  1  2  3  5  6  78  150  123  43  45  99  20  12
  1  2  3  5  6  12  150  123  43  45  99  20  78
  1  2  3  5  6  12  20  123  43  45  99  150  78
  1  2  3  5  6  12  20  43  123  45  99  150  78
  1  2  3  5  6  12  20  43  45  123  99  150  78
  1  2  3  5  6  12  20  43  45  78  99  150  123
  1  2  3  5  6  12  20  43  45  78  99  150  123
  1  2  3  5  6  12  20  43  45  78  99  123  150
  1  2  3  5  6  12  20  43  45  78  99  123  150


Above output will show the array elements position at the end of each iteration.

No comments:

Post a Comment