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]

Tagged , , , , , , . Bookmark the permalink.

One Response to Bubble Sorting A String Array in Ascending And Descending Order

  1. Ririn says:

    Thanks buat script codenya, membantu saya mengerkajan tugas saya

Leave a Reply

Your email address will not be published. Required fields are marked *