Selection Sort is a simple comparison-based sorting algorithm. It divides the array into two parts:
In each iteration, it:
Despite its simplicity, it’s not efficient for large datasets.
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);
}
}
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
[64, 25, 12, 22, 11]
i = 0Find the minimum from i=0 to end → 11
[64, 25, 12, 22, 11]
→ 11 is the smallest → swap with 64
→ [11, 25, 12, 22, 64]
i = 1Find the minimum from i=1 to end → 12
[11, 25, 12, 22, 64]
→ 12 is the smallest → swap with 25
→ [11, 12, 25, 22, 64]
i = 2Find the minimum from i=2 to end → 22
[11, 12, 25, 22, 64]
→ 22 is the smallest → swap with 25
→ [11, 12, 22, 25, 64]
i = 3Find the minimum from i=3 to end → 25
[11, 12, 22, 25, 64]
→ already in place
→ no swap
[11, 12, 22, 25, 64]