选择排序思想
每一次遍历数组,都会求出一个最小值/最大值, 然后与当前元素交换
code
public static void selectedSort(int[] arr){
if (arr == null || arr.length < 2){
return;
}
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i; // 记录最小值下标
for (int j = i + 1; j < arr.length; j++) {
minIndex = arr[j] < arr[minIndex] ? j : minIndex;
}
if (i != minIndex){
int tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
}
test
这里就直接条用冒泡排序里写好的比较器进行测试
public static void main(String[] args) {
int testTime = 500000;
int maxSize = 100;
int maxValue = 100;
boolean succeed = true;
for (int i = 0; i < testTime; i++) {
int[] array = Code_01_BubbleSort.generateRandomArray(maxSize, maxValue);
int[] array1 = Code_01_BubbleSort.copyArray(array);
int[] array2 = Code_01_BubbleSort.copyArray(array);
selectedSort(array1);
Code_01_BubbleSort.comparator(array2);
if (!Code_01_BubbleSort.isEqual(array1, array2)){
succeed = false;
break;
}
}
System.out.println(succeed ? "nice" : "ddddd");
int[] temp = Code_01_BubbleSort.generateRandomArray(maxSize,maxValue);
selectedSort(temp);
Code_01_BubbleSort.printArray(temp);
}