How to implement the selection sort algorithm in the Java language?
Here is an example of implementing the selection sort algorithm in Java.
public class SelectionSort {
public static void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
sort(arr);
System.out.println("排序后的数组:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
This code demonstrates how to implement the selection sort algorithm in Java. The sort() method takes an array of integers as a parameter, and uses nested loops to find the smallest element and swap it with the current position. In the end, the elements in the array are arranged in ascending order.
In the main function, we created an integer array called arr and sorted it using the sort() method. Afterwards, we printed the sorted array using a for-each loop.