Implementation of the Selection Sort algorithm in Java

Data Structure Sorting (Article) Sorting (Program)

106

Given Input:

Original array:
64 25 12 22 11 


Expected Output:

Sorted array:
11 12 22 25 64 

Program:

public class SelectionSort {
    
    // Function to perform selection sort
    public static void selectionSort(int[] array) {
        int n = array.length;
        
        // One by one, move the boundary of the unsorted subarray
        for (int i = 0; i < n - 1; i++) {
            // Find the minimum element in the unsorted array
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            
            // Swap the found minimum element with the first element
            int temp = array[minIndex];
            array[minIndex] = array[i];
            array[i] = temp;
        }
    }
    
    // Function to print the array
    public static void printArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        int[] array = {64, 25, 12, 22, 11};
        
        System.out.println("Original array:");
        printArray(array);
        
        // Perform selection sort
        selectionSort(array);
        
        System.out.println("Sorted array:");
        printArray(array);
    }
}

Output:

Original array:
64 25 12 22 11 
Sorted array:
11 12 22 25 64 

Explanation:

  • Outer Loop: The outer loop runs through each index in the array, considering it the starting point of the unsorted part of the array.
  • Inner Loop: The inner loop finds the smallest element in the unsorted portion of the array.
  • Swapping: Once the minimum element is found, it's swapped with the element at the beginning of the unsorted part of the array.
  • Time Complexity: Selection sort has a time complexity of O(n²), where n is the number of elements in the array.

This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.