How to write Java code for selection sort?
Here is a code example of a simple selection sort algorithm in Java.
public class SelectionSort {
public static void main(String[] args) {
int[] array = {5, 2, 6, 1, 3, 4}; // 待排序的数组
selectionSort(array); // 调用选择排序算法进行排序
for (int num : array) {
System.out.print(num + " "); // 输出排序后的数组
}
}
public static void selectionSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
swap(array, i, minIndex); // 将当前位置的数与最小值交换
}
}
public static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
In this code example, we have defined a selection sort function called selectionSort, which takes an integer array as a parameter. The function uses two loops to implement the logic of selection sort. The outer loop is used to iterate through each element in the array, while the inner loop is used to find the smallest element in the unsorted portion. The index of the smallest element is stored in the minIndex variable. After the inner loop ends, we swap the current position’s number with the minimum value by calling the swap function. Finally, we call the selectionSort function in the main function and output the sorted array.