Selection Sort

Java 19.6.2015 No Comments

The algorithm finds the minimum value, swaps it with the value in the first position, and repeats these steps for the remainder of the list. It does no more than n swaps, and thus is useful where swapping is very expensive.

Selection Sort, Wikipedia

When you are learning Java you are very likely going to be asked to write a program to sort values. We will start with one of the simpler sort algorithms, the Selection Sort (also known as an Exchange Sort). It’s not a particularly efficient algorithm and really only suitable for small lists.

package com.learnjava.math.sort;

import java.util.Random;

/**
 * Write a program to sort an array of numbers using a Selection Sort
 * Also known as an Exchange Sort
 *
 * @author https://learn-java-by-example.com
 *
 */
public class SelectionSort {

	public static void main(String[] args) {

		// Create an array of random numbers to sort

		int[] data = generateData();

		// Display the unsorted data

		System.out.println("Unsorted data:");
		printArray(data);

		// Sort the array

		sortArray(data);

		// Display the sorted data

		System.out.println("Sorted data:");
		printArray(data);
	}

	private static void sortArray(int[] data) {

		// Loop through the array,
		// comparing each value with each of the following values

		for (int i=0; i<data.length-1; i++) {
			for (int j=i+1; j<data.length; j++) {

				// Check if the value needs to be swapped or not

				if (data[i] < data[j]) {

					// Swap values

					int temp = data[i];
					data[i] = data[j];
					data[j] = temp;
				}
			}

			// Print out the array after we have
			// finished each element to see the progress

			System.out.println("Loop " + i);
			printArray(data);
		}
	}

	private static int[] generateData() {
		Random random = new Random();

		int[] data = new int[10];
		for (int i=0; i<data.length; i++) {
			data[i] = random.nextInt(100);
		}
		return data;
	}

	private static void printArray(int[] data) {
		for (int i=0; i<data.length; i++) {
			System.out.print(data[i]);
			System.out.print(", ");
		}
		System.out.println();
	}
}

Leave a Reply

s2Member®