Selection Sort Algorithm in Java

Selection sort is one of the simplest sorting algorithms. It is easy to implement but it is not very efficient.

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

https://en.wikipedia.org/wiki/Selection_sort

Following Java class shows how to implement Selection sort in Java.

package com.zparacha.algorithms;

import java.util.Arrays;

/**
 * Selection Sort Implementation In Java
 * 
 * @author zparacha
 *
 * @param <T>
 */
public class SelectionSort<T extends Comparable<T>> {
	int size;
	T[] data;

	public SelectionSort(int n) {
		data = (T[]) new Comparable[n];
	}

	public void insert(T a) {
		data[size++] = a;
	}

	public boolean isSmaller(T x, T y) {
		return x.compareTo(y) < 0;
	}

	public void swap(int i, int y) {
		T temp = data[i];
		data[i] = data[y];
		data[y] = temp;
	}

	public void selectionSort() {
		for (int i = 0; i < size; i++) {
			int minIndex = i; //set the minIndex to current element
			for (int j = i + 1; j < size; j++) {
				//compare the value of current element with remaining elements in 
				// the array. If a value smaller than current value is found, set the
				//minIndex to that value's index and keep comparing until end of 
				//array. 
				if (isSmaller(data[j], data[minIndex])) {
					minIndex = j;
				}
			}
			//if minIndex is different than the current value, it means 
			//that current value is not the smallest, swap it with the smallest value. 
			if (minIndex != i) {
				swap(i, minIndex);
			}
		}
	}

	public static void main(String[] args) {
		SelectionSort<Integer> ss = new SelectionSort<>(5);
		ss.insert(4);
		ss.insert(3);
		ss.insert(1);
		ss.insert(5);
		ss.insert(2);
		System.out.println(Arrays.toString(ss.data));
		ss.selectionSort();
		System.out.println(Arrays.toString(ss.data));
	}
}