Java Code Implementation Of Selection Sort

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n^2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.

The algorithm works as follows:

1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)

Effectively, we divide the list into two parts: the sublist of items already sorted, which we build up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

Selection sort can also be used on list structures that make add and remove efficient, such as a linked list. In this case it’s more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far.

Variants of Selection Sort:
Heapsort greatly improves the basic algorithm by using an implicit heap data structure to speed up finding and removing the lowest datum. If implemented correctly, the heap will allow finding the next lowest element in T(log n) time instead of T(n) for the inner loop in normal selection sort, reducing the total running time to T(n log n).

A bidirectional variant of selection sort, called cocktail sort, is an algorithm which finds both the minimum and maximum values in the list in every pass. This reduces the number of scans of the list by a factor of 2, eliminating some loop overhead but not actually decreasing the number of comparisons or swaps. Note, however, that cocktail sort more often refers to a bidirectional variant of bubble sort.

Selection sort can be implemented as a stable sort. If, rather than swapping in step 2, the minimum value is inserted into the first position (that is, all intervening items moved down), the algorithm is stable. However, this modification either requires a data structure that supports efficient insertions or deletions, such as a linked list, or it leads to performing T(n^2) writes. Either way, it eliminates the main advantage of insertion sort (which is always stable) over selection sort.

In the bingo sort variant, items are ordered by repeatedly looking through the remaining items to find the greatest value and moving all items with that value to their final location. Like counting sort, this is an efficient variant if there are many duplicate values. Indeed, selection sort does one pass through the remaining items for each item moved. Bingo sort does two passes for each value (not item): one pass to find the next biggest value, and one pass to move every item with that value to its final location. Thus if on average there are more than two items with each value, bingo sort may be faster.

(Source Of The Above Text: Wikipedia
Text is available under the Creative Commons Attribution/Share-Alike License)
———————————-

The following is my implementation of Selection Sort in Java.

Insertion Sort Implementation In Java – Working Code Example

Insertion Sort Animation. Image Credit: Wikipedia / Creative Commons

Algorithm:

  • Take one element, compare with the one next to it and put in the order it belongs to, thus forming a partially sorted list.
  • Iterate through the list, one item at a time until no input elements remain.

Pseudo code is given below:

for i ← 1 to length(A)
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1

Complexity:

  • Best Case: O(n) – For already sorted list
  • Average Case: O(n^2)
  • Worst Case: O(n^2)

Notes / Usage:

  • Insertion Sort is:
    • Stable
    • Takes O(1) extra space for swapping
    • In-Place Sorting – No extra memory is required
  • One real life usage of this kind of sorting is sorting a deck of cards.

Java Implementation Code:

package com.icodejava.blog.datastructure;

import java.util.Arrays;

/**
* @author Kushal Paudyal
* www.icodejava.com
* Created On -  Feb 26, 2014
* Last Modified On - Feb 26, 2014
*/
public class InsertionSort {

public static void main(String args[]) {
    int[] numberArray = { 5, 4, 7, 3, 3, 9, 0, 1, 2, 8, 6, -5 };

    sort(numberArray);

}

public static void sort(int[] numberArray) {

     System.out.println("Input Array: " + Arrays.toString(numberArray));

     for (int i = 1; i < numberArray.length; i++) { 			
         for (int j = i; j > 0; j--) {
             // Start comparing data with adjacent one and swap if smaller
             if (numberArray[j] < numberArray[j - 1]) {
             swap(numberArray, j, j - 1);
         }
     }
}

System.out.println("Sorted Array: " + Arrays.toString(numberArray));

}

/**
* Swaps data from an array.
*/
private static void swap(int[] array, int firstIndex, int secondIndex) {
   if (array == null || firstIndex < 0 || firstIndex > array.length 
     || secondIndex < 0 || secondIndex > array.length) {
    return;
   }
   int temp = array[firstIndex];
   array[firstIndex] = array[secondIndex];
   array[secondIndex] = temp;

}

}


Output of running above program:

Input Array: [5, 4, 7, 3, 3, 9, 0, 1, 2, 8, 6, -5]
Sorted Array: [-5, 0, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9]

Selection Sort Implementation In Java – Working Code Example

Algorithm:

  • First find the smallest element in the array and exchange it with the element in the first position.
  • Then find the second smallest element and exchange it with the element in the second position.
  • Continue in this way until the entire array is sorted.

Complexity:

  • Best Case: n^2
  • Average Case: n^2
  • Worst Case: n^2

Notes:

  • Selection sort is an in-place comparison sort – thus taking O(1) memory space.
  • Selection sort is not stable**
  • Selection sort is a very simple algorithm
  • This sort is inefficient on large arrays.
  • Useful if less data movement is required. Selection sort has the lowest data movement. Useful when writing to Flash Memory.

When to use Selection Sort?

  • If the data is of small size
  • If I/O operations are more (since Selection Sort only writes n number of times). Specially when the sorting is done on a file rather than in memory
  • If simplicity is required rather than performance

**A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input unsorted array. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort
Java Implementation:

package com.icodejava.blog.datastructure;

import java.util.Arrays;

/**
 * @author Kushal Paudyal
 * www.icodejava.com
 * Created On -  Feb 25, 2014
 * Last Modified On - Feb 25, 2014
 */
public class SelectionSort {

	public static void main(String args[]) {
		int[] numberArray = { 5, 4, 7, 3, 3, 9, 0, 1, 2, 8, 6, -5 };

		sort(numberArray);

	}

	public static void sort(int[] numberArray) {
		System.out.println("Input Array: " + Arrays.toString(numberArray));
		for (int i = 0; i < numberArray.length-1; i++) {
			int minIndex = i;
			for (int j = i+1; j < numberArray.length; j++) {
				if (numberArray[j] < numberArray[minIndex]) {
					minIndex = j;
				}

			}

			if(minIndex != i) {
				swap(numberArray, minIndex, i);
			}

		}

		System.out.println("Sorted Array: " + Arrays.toString(numberArray));
	}

	/**
	 * Swaps data from an array.
	 */
	private static void swap(int[] array, int firstIndex, int secondIndex) {
		if (array == null || firstIndex < 0 || firstIndex > array.length
				|| secondIndex < 0 || secondIndex > array.length) {
			return;
		}
		int temp = array[firstIndex];
		array[firstIndex] = array[secondIndex];
		array[secondIndex] = temp;

	}
}

Here is the output of running above Selection Sort program:

Input Array: [5, 4, 7, 3, 3, 9, 0, 1, 2, 8, 6, -5]
Sorted Array: [-5, 0, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9]