Selection Sort Algorithm

A simple example of the selection sort algorithm.

Running a test file of 100000 randomly ordered integers through this algorithm takes about 4.72 seconds on my system. I will be using the same test file for comparison against other sorting algorithms.

Josh


/**
 * A very basic Selection Sort class.
 * 
 * This class will only sort an int[].
 * 
 * @author Joshua Weise
 */
public class SelectionSort {

	// array of numbers
	private int[] data;
	
	public SelectionSort(int[] data) {
		this.data = data;
	}
	
	// selection sort data
	public void sort() {
		// move right through our array
		for (int i = 0; i < data.length; i++) {
			// assign the first location as our assumed smallest number
			int smallest = i;
			// loop through the rest of array checking for smaller numbers
			for (int j = 1+i; j < data.length; j++) {
				if (data[j] < data[smallest]) {
					smallest = j;
				}
			}
			// swap number locations
			swap(i, smallest);
		}
	}
	
	// swaps data in place at locations a and b in the array
	private void swap(int a, int b) {
		int z = data[a];
		data[a] = data[b];
		data[b] = z;	
	}
	
	// return data
	public int[] getData() {
		return data;
	}
}

This entry was posted in Java, Sorting Algorithms. Bookmark the permalink.

Leave a Reply