选择排序(Selection Sort)
选择排序是一种简单的排序算法,它的基本思想是每次从待排序的元素中选出最小(或最大)
的一个元素,存放在序列的起始位置,直到全部待排序的元素排完。
import org.junit.jupiter.api.Assertions;
import java.util.Arrays;
public class Selection {
public static void selectionSort(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;
}
}
// 交换 arr[i]和 arr[minIndex]
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1, 6};
int[] expectedArr = {1, 2, 3, 5, 6, 8};
Selection.selectionSort(arr);
System.out.println("arr = " + Arrays.toString(arr));
Assertions.assertArrayEquals(expectedArr, arr);
}
}
在上面的代码中, selectionSort 函数接受一个整数数组作为输入,并使用选择排序算法对
其进行排序。外部循环运行 n - 1 次,其中 n 是数组的长度。在内部循环中,我们找到未
排序部分中的最小元素,并将其索引存储在 minIndex 变量中。然后,我们将最小元素与已
排序部分的末尾交换。在每次外部循环迭代后,已排序部分的长度增加 1,未排序部分的长
度减少 1。
选择排序的时间复杂度为 O(n^2),这使得它在大型列表和实际应用中效率低下。但是,由于
其简单性,它是向初学者教授排序的好算法。