选择排序是一种简单直观的排序算法,其基本思想是在未排序的序列中找到最小(或最大)的元素,并将其放到序列的起始位置,然后从剩余未排序的元素中继续寻找最小(或最大)的元素,放到已排序序列的末尾。这个过程会重复进行,直到整个序列排序完成。
选择排序在Java中的实现如下:
```java
public class SelectSort {
public static void main(String[] args) {
int[] arr = {6, 3, 8, 2, 9, 1};
selectionSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void selectionSort(int[] a) {
if (a == null || a.length == 0) {
return;
}
for (int i = 0; i < a.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = a[minIndex];
a[minIndex] = a[i];
a[i] = temp;
}
}
}
}
选择排序的时间复杂度为O(n^2),其中n是数组的长度。它不适合大规模数据的排序,因为其效率较低。如果需要高效排序,可以考虑使用快速排序、归并排序或堆排序等更高级的排序算法。