Selection Sort in Java

Selection sort is a simple sorting algorithm that sorts an array by repeatedly finding the minimum element (or maximum element) from the unsorted part of the array and moving it to the beginning (or end) of the sorted part of the array.


Here's an example implementation of selection sort in Java:

public class SelectionSortExample {
    public static void selectionSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            // Swap arr[i] and arr[minIndex]
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }

    public static void main(String[] args) {
        int[] arr = { 64, 25, 12, 22, 11 };
        selectionSort(arr);
        System.out.println("Sorted array:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}


This program defines a class SelectionSortExample with a selectionSort method that takes an integer array arr, and sorts it using the selection sort algorithm. The main method creates an example array arr, calls the selectionSort method with this array, and then prints the sorted array.


The selectionSort method works by first setting the size of the array n, and then looping over the array n-1 times. On each iteration, it finds the index of the minimum element in the unsorted part of the array, by looping over the remaining unsorted elements of the array and comparing them to the current minimum element. Once the minimum element is found, it is moved to the beginning of the sorted part of the array, by swapping it with the first element of the unsorted part of the array. The outer loop continues until all elements are sorted.


In the example above, the input array is { 64, 25, 12, 22, 11 }. After the first iteration of the outer loop, the minimum element 11 is moved to the beginning of the array, and the array becomes { 11, 25, 12, 22, 64 }. After the second iteration, the minimum element 12 is moved to the second position, and the array becomes { 11, 12, 25, 22, 64 }, and so on, until the array is completely sorted.