选择排序(Select Sorting)的基本思想
第一次从arr[0] ~ arr[n-1]中选取最小值,与arr[0]交换,第二次从arr[1] ~ arr[n-1]中选取最小值,与arr[1]交换,第三次从arr[2] ~ arr[n-1]中选取最小值,与arr[2]交换,…,第i次从arr[i-1] ~ arr[n-1]中选取最小值,与arr[i-1]交换,…, 第n-1次从arr[n-2] ~ arr[n-1]中选取最小值,与arr[n-2]交换,总共通过n-1次,得到一个按排序码从小到大排列的有序序列。
代码实现
public class SelectSort {
public static void main(String[] args) {
int[] nums = new int[]{10, 2, 11, 56, 0, 8, 90, 22, 1, 66};
for (int num : nums) {
System.out.print(num + "\t");
}
System.out.println();
selectSort(nums);
for (int num : nums) {
System.out.print(num + "\t");
}
System.out.println();
}
public static void selectSort(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
// minIndex用来保存每一趟比较的最小值的索引,假设当前最小值的下标为i
int minIndex = i;
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] < nums[minIndex]) {
// 重置最小值的下表
minIndex = j;
}
}
if (i != minIndex) {
int temp = nums[i];
nums[i] = nums[minIndex];
nums[minIndex] = temp;
}
}
}
}
结果
10 2 11 56 0 8 90 22 1 66
0 1 2 8 10 11 22 56 66 90
时间复杂度:O(n^2)