算法步骤
![在这里插入图片描述](https://img-blog.csdnimg.cn/img_convert/8c42ffa5ab7186aa7f09e4ce68e338b9.png#pic_center)
- 核心思想:将数组分为已排序和未排序两种情况,
- 先把未排序的第一个array[i]的下标用minIndex保存起来,再遍历数组,
- 把比array[i] 小的数的下标赋值给minIndex ,
- 等一趟遍历结束,将未排序的第一个元素与下标为minIndex的元素进行交换位置。
代码演示
import java.util.Arrays;
public class Test2 {
public static void main(String[] args) {
int[] array = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};
System.out.println("排序前:" + Arrays.toString(array));
selectSort(array);
System.out.println("排序后:" + Arrays.toString(array));
}
public static void selectSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int minIndex = i;
for (int j = i+1; j < array.length; j++) {
if(array[minIndex] > array[j]){
minIndex = j;
}
}
if(minIndex != i){
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
}
}
运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210330140151722.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTAzMzIzMQ==,size_16,color_FFFFFF,t_70)