/**
* @author zzw
* @create 2021/04/11-14:41
*/
//得到最大值的下标,将它放到倒数第一,得到第二大的数的下标,放到倒数第二位置,重复
public class test {
public static void main(String[] args) {
int[] arrays = {1, 5, 8, 2, 4, 9, 6, 8};
//交换的变量
int temp;
//外层循环控制需要排序的趟数
for (int i = 0; i < arrays.length - 1; i++) {
//记录当前趟数的最⼤值的下标,新的趟数,每次都将⻆标重新赋值为0
int pos = 0;
//内层循环控制遍历数组的个数并得到最⼤数的⻆标
for (int j = 0; j < arrays.length - i; j++) {
//得到最大值的下标
if (arrays[j] > arrays[pos]) {
pos = j;
}
}
//交换值
temp = arrays[pos];
arrays[pos] = arrays[arrays.length - 1 - i]; //1.将当前最末尾的值放到最大值的下标位置
arrays[arrays.length - 1 - i] = temp; //2.将最大值放到当前最末尾的下标处。
}
//遍历得到的数组
for (int array : arrays) {
System.out.print(array+" ");
}
}
}
02--选择排序
最新推荐文章于 2023-12-31 23:53:21 发布