JAVA: Selection Sort - rFronteddu/general_wiki GitHub Wiki
Selection Sort
public class SelectionSort {
// Function to perform selection sort
public static void selectionSort(int[] array) {
int n = array.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in 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
swap (minIndex, i);
}
}
// Utility function to print the array
public static void printArray(int[] array) {
int n = array.length;
for (int i = 0; i < n; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
// Main method to test the selection sort
public static void main(String[] args) {
int[] array = {64, 25, 12, 22, 11};
System.out.println("Unsorted array:");
printArray(array);
selectionSort(array);
System.out.println("Sorted array:");
printArray(array);
}
}