- 基本思想;每次查找最小的数,和其应有的位置进行交换
public class SelectionSort {
public static void sort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
for (int i = 0; i < nums.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] < nums[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(nums, minIndex, i);
}
}
}
private static void swap(int[] nums, int n1, int n2) {
if (n1 >= nums.length || n2 >= nums.length) {
throw new RuntimeException("n1 or n2 illegal");
}
int temp = nums[n1];
nums[n1] = nums[n2];
nums[n2] = temp;
}
}