Selection Sort Algorithm

Selection Sort is a simple comparison-based sorting algorithm. It divides the array into two parts:

  • The sorted part at the beginning
  • The unsorted part at the end

In each iteration, it:

  1. Finds the minimum element in the unsorted part.
  2. Swaps it with the first element of the unsorted part.

Time Complexity

  • Best case: O(n²)
  • Average case: O(n²)
  • Worst case: O(n²)

Despite its simplicity, it’s not efficient for large datasets.

Code Example

public class SelectionSortExample {

    public static void selectionSort(int[] arr) {
        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;

            // Find the index of the minimum element in unsorted part
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }

            // Swap the found minimum with the first element of unsorted part
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;

            // Print the array after each pass
            printArray(arr);
        }
    }

    public static void printArray(int[] arr) {
        for (int value : arr) {
            System.out.print(value + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        System.out.println("Original array:");
        printArray(arr);

        System.out.println("\nSorting steps:");
        selectionSort(arr);

        System.out.println("\nSorted array:");
        printArray(arr);
    }
}

Output

Original array:
64 25 12 22 11 

Sorting steps:
11 25 12 22 64 
11 12 25 22 64 
11 12 22 25 64 
11 12 22 25 64 

Sorted array:
11 12 22 25 64 

Visual Explanation (Step-by-Step)

Initial Array:
[64, 25, 12, 22, 11]

🔁 Pass 1: i = 0

Find the minimum from i=0 to end11

[64, 25, 12, 22, 11]  
→ 11 is the smallest → swap with 64  
→ [11, 25, 12, 22, 64]

🔁 Pass 2: i = 1

Find the minimum from i=1 to end12

[11, 25, 12, 22, 64]  
→ 12 is the smallest → swap with 25  
→ [11, 12, 25, 22, 64]

🔁 Pass 3: i = 2

Find the minimum from i=2 to end22

[11, 12, 25, 22, 64]  
→ 22 is the smallest → swap with 25  
→ [11, 12, 22, 25, 64]

🔁 Pass 4: i = 3

Find the minimum from i=3 to end25

[11, 12, 22, 25, 64]  
→ already in place  
→ no swap

✅ Final Sorted Array:
[11, 12, 22, 25, 64]