初始时在序列中找到最小(大)元素,放到序列的起始(末尾)位置作为已排序序列;然后,再从剩余未排序元素中继续寻找最小(大)元素,放到已排序序列的尾部(首部)。以此类推,直到所有元素均排序完毕。
以找最小元素为例:
import java.util.Arrays; /** * @author wylu */ public class SelectSort { public static void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } /** * 每一轮选择最大元素 * @param arr 待排序数组 */ public static void maxSelectSort(int[] arr) { for (int i = arr.length - 1; i > 0; i--) { int maxIdx = i; for (int j = 0; j < i; j++) { if (arr[j] > arr[maxIdx]) { maxIdx = j; } } swap(arr, maxIdx, i); } } /** * 每一轮选择最小元素 * @param arr 待排序数组 */ public static void minSelectSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int minIdx = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIdx]) { minIdx = j; } } swap(arr, minIdx, i); } } public static void main(String[] args) { int[] arr = {3, 1, 4, 9, 6, 0, 7, 2, 5, 8}; SelectSort.maxSelectSort(arr); System.out.println(Arrays.toString(arr)); int[] arr2 = {12, 8, 30, 25, -1, 0 , 17, 8, 10}; SelectSort.minSelectSort(arr2); System.out.println(Arrays.toString(arr2)); } }
排序算法 | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 排序方式 | 稳定性 |
---|---|---|---|---|---|---|
选择排序 | In-place | 不稳定 |