Selection Sort is a simple comparison-based sorting algorithm. It works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the array and placing it in its correct position. In each pass, the unsorted portion of the array becomes smaller, while the sorted portion grows.
The algorithm performs n − 1 passes for an array containing n elements. During each pass, the inner loop finds the smallest (or largest) element in the unsorted portion of the array, and the outer loop swaps it with the first unsorted element, placing it in its correct position.
The following example illustrates how the Selection Sort algorithm works with the help of a diagram.
SelectionSort.java,
package com.test; public class SelectionSort { public static int[] sortArray(int[] arr){ for (int i = 0; i < arr.length - 1; i++) { int index = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[index]) { index = j;
}
}
int minNumber = arr[index];
arr[index] = arr[i];
arr[i] = minNumber;
}
return arr;
}
public static void printArray(int[] arr) { for (int i=0; i<arr.length; i++) { System.out.print(arr[i]+" "); } } public static void main(String a[]){ int[] arr1 = {8,10,2,43,12,92,58,62}; System.out.println("Array before Sorting,"); printArray(arr1); System.out.println(""); int[] arr2 = sortArray(arr1); System.out.println("Array after sorting,"); printArray(arr2); } }
Output :-
Array before Sorting,
8 10 2 43 12 92 58 62
Array after sorting,
2 8 10 12 43 58 62 92
Complexity:--
Selecting the smallest element requires scanning all n elements, which takes n − 1 comparisons. The selected element is then swapped with the first element in the array.
Finding the next smallest element requires scanning the remaining n − 1 elements, and the process continues until the array is completely sorted.
The total number of comparisons is:
(n − 1) + (n − 2) + ... + 2 + 1
= n(n − 1) / 2
= O(n²)
Time Complexity
Best Case: O(n²)
Average Case: O(n²)
Worst Case: O(n²)
Note: Although both Selection Sort and Bubble Sort have a time complexity of O(n²), Selection Sort is generally more efficient because it performs significantly fewer swaps. Selection Sort makes at most n − 1 swaps, whereas Bubble Sort may perform many more swaps, resulting in higher overhead.
1) Java Program for Bubble Sort in Ascending and Descending order
2) Java Program to Sort ArrayList of Custom Objects By Property using Comparator interface
3) Difference between Comparable and Comparator Interface in Java



