Selection Sort Algorithm

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Selection Sort Algorithm

This Java example program introduces selection sort algorithm.

[edit] Java Source Code

  • Package: example.sortsearch
  • File: SelectionSort.java
package example.sortsearch;
 
public class SelectionSort {
    private long[] a;
 
    private int nElems;
 
    public SelectionSort(int max) {
	a = new long[max];
	nElems = 0;
    }
 
    public void insert(long value) {
	a[nElems] = value;
	nElems++;
    }
 
    public void display() {
	for (int j = 0; j < nElems; j++)
	    System.out.print(a[j] + " ");
	System.out.println("");
    }
 
    public void selectionSort() {
	int out, in, min;
 
	for (out = 0; out < nElems - 1; out++) // outer loop
	{
	    min = out; // minimum
	    for (in = out + 1; in < nElems; in++)
		// inner loop
		if (a[in] < a[min]) // if min greater,
		    min = in; // a new min
	    swap(out, min); // swap them
	}
    }
 
    private void swap(int one, int two) {
	long temp = a[one];
	a[one] = a[two];
	a[two] = temp;
    }
 
    public static void main(String[] args) {
	int maxSize = 100;
	SelectionSort arr; // reference to array
	arr = new SelectionSort(maxSize); // create the array
 
	arr.insert(17); // insert 10 items
	arr.insert(29);
	arr.insert(34);
	arr.insert(45);
	arr.insert(52);
	arr.insert(68);
	arr.insert(71);
	arr.insert(80);
	arr.insert(96);
	arr.insert(33);
 
	arr.display();
 
	arr.selectionSort();
 
	arr.display();
    }
 
}

[edit] What Result You Can Get

Coming soon... Run the program, you will get:

17 29 34 45 52 68 71 80 96 33 
17 29 33 34 45 52 68 71 80 96 

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.

http://www.ase2009.com/ online casino 132 http://www.hellzyea.com/health health insurance 8DDD http://www.yourautoinsurancesite.com/ auto insurance quotes 135811 http://www.makemeasammich.com/ auto insurance mcnxu

[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools