Program Structure
The Selection Sort algorithm sorts an array by repeatedly finding the minimum element from the unsorted part and moving it to the beginning. The process continues until the array is sorted.
Java Code
/**
* This class implements the Selection Sort algorithm.
*/
public class SelectionSort {
/**
* The method to perform selection sort on an array.
*
* @param arr The array to be sorted.
*/
public static void selectionSort(int[] arr) {
int n = arr.length;
// Traverse through all array elements
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 (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
/**
* A utility method to print the contents of an array.
*
* @param arr The array to print.
*/
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
/**
* Main method to test the selection sort algorithm.
*
* @param args Command line arguments.
*/
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("Original array:");
printArray(arr);
selectionSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Explanation of the Code
The program consists of a class named SelectionSort
which contains the following methods:
- selectionSort(int[] arr): This method implements the selection sort algorithm. It iterates through the array, finds the minimum element in the unsorted portion, and swaps it with the first unsorted element.
- printArray(int[] arr): A utility method that prints the elements of the array.
- main(String[] args): The entry point of the program, which initializes an array, calls the sorting method, and prints the original and sorted arrays.
How to Run the Program
To run this program, you need to have Java installed on your machine. Save the code in a file named SelectionSort.java
, and then follow these commands in your terminal:
javac SelectionSort.java
java SelectionSort
Conclusion
Selection Sort is a simple sorting algorithm that is inefficient on large lists. However, it is easy to understand and implement, making it suitable for educational purposes.