Selection Sort Implementation in Java

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


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() {
			int minIndex = i; //set the minIndex to current element
				//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 
				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);


Leave a Reply
