选择排序是一种简单直观的排序算法,其基本思想是每次从未排序的部分中找到最小(或最大)的元素,并将其放到已排序部分的末尾。下面是使用Java实现选择排序的代码示例:
```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;
}
}
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
}
这段代码定义了一个名为`SelectionSort`的类,其中包含`main`方法和`selectionSort`方法。`main`方法用于测试排序算法,而`selectionSort`方法实现了选择排序算法的核心逻辑。
选择排序的时间复杂度为O(n^2),空间复杂度为O(1)。