📌 Information & Algorithm

Given Input:

Original array:
64 25 12 22 11 


Expected Output:

Sorted array:
11 12 22 25 64 

💻 Program Code

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);
    }
}

                        

🖥 Program 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.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.