Java ProgramsArraysSelection Sort

Selection Sort in Java

intermediate·  Arrays  ·  Sorting

Problem

Selection sort repeatedly finds the smallest value in the unsorted part of the array and swaps it into place at the front, growing the sorted section by one element each pass.

Given an array of integers, sort it in ascending order using selection sort.

Input
[6, 2, 8, 4, 1]
Output
[1, 2, 4, 6, 8]

Java Program

Java
import java.util.Arrays; public class SelectionSort { public static void main(String[] args) { int[] arr = {6, 2, 8, 4, 1}; for (int i = 0; i < arr.length - 1; i++) { int minIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; // track the position of the smallest value found so far } } int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } System.out.println(Arrays.toString(arr)); } }

Output

[1, 2, 4, 6, 8]

Core Logic

Repeatedly scanning the unsorted section for its smallest element and swapping it to the front grows a sorted prefix one element at a time.

How It Works
  1. 1The outer loop runs i from 0 to arr.length - 2, marking the boundary between the sorted and unsorted sections.
  2. 2minIndex starts at i, assuming the current position holds the smallest remaining value.
  3. 3The inner loop scans from i + 1 to the end, updating minIndex whenever a smaller value is found.
  4. 4After the inner loop, arr[i] and arr[minIndex] are swapped, placing the smallest remaining value at position i.
For [6, 2, 8, 4, 1], the first pass scans for the smallest value (1, at index 4) and swaps it into index 0, producing [1, 2, 8, 4, 6] — repeating this grows the sorted prefix until the array is fully sorted.
💡

Key Point: Unlike bubble sort, which swaps on every out-of-order pair it finds, selection sort does at most one swap per outer-loop pass — it only swaps once the smallest remaining value has actually been located.

Complexity
Time Complexity: O(n²)Space Complexity: O(1)

Why: The nested loops compare roughly n²/2 pairs to find each pass's minimum, and the swap happens in place using only a temp variable.

Key Concepts

nested for looprunning minimum indexswap

Related Programs