Selection Sort | Sort Code | Sorting Algorithms Java

Selection sort is simple sorting algorithm. This Sort code is a set up correlation based calculation in which the array is divided into two sections, the arranged part at the left end and the unsorted part at the right end. At first, the arranged part is vacant and the unsorted part is the whole array.Code of Selection sort Algorithm: is given below:

There are two .java classes for the Selection sort Algorithm:

  1. Runner class.
  2. Sort Class.

Following Figure illustrates the algorithm of Selection sort  that how this algorithms works:

 

Selection Sorting Algorithm

Selection sort

Code is successfully compiled on the Eclipse compiler:

Sort Code:

Runner Class:

package selection_sort;

public class Runner {

public static void main(String[] args) {
int maxSize = 100;
Sort sort = new Sort(maxSize);

sort.insert(77);
sort.insert(99);
sort.insert(44);
sort.insert(55);
sort.insert(22);
sort.insert(88);
sort.insert(11);
sort.insert(00);
sort.insert(66);
sort.insert(33);

// sort.display();
sort.Selection_Sort();

// sort.display();
}

}

Sort Class:

package selection_sort;

public class Sort {

private long[] a;
private int nElems;

public Sort(int max)
{
a = new long[max];
nElems = 0;
}
public void insert(long value)
{
a[nElems] = value;
nElems++;
}
public void display()
{
for(int i=0; i<nElems; i++)
{
System.out.print(a[i] + ” “);
}
System.out.println();
}
public void Selection_Sort()
{
int out, in , min;

for(out = 0; out <nElems-1; out++)
{
min = out;
for(in = out+1; in<nElems; in++)
{
if(a[in]< a[min])
{
min = in;
swap(out,min);
for(int i=0; i<nElems ; i++)
{
System.out.print(a[i]+”.”);
}
System.out.println();
}

}System.out.println();
}
}
public void swap(int one, int two)
{
long temp = a[one];

a[one]= a[two];
a[two] = temp;
}
}

Related Articles:

Note: This code is run on eclispse and netbeans compiler for several time successfully. Make sure you make the seperate clasees of Runner and Sort and place the above code inside those classes

 

Comment if you have any confusion or query thanks !!!;

24 Comments

Add a Comment

Your email address will not be published. Required fields are marked *