/** * @author WanJl * @version 1.0 * @title HomeWork02 * @description 7月16日作业-选择排序(降序)-选最大的 * @create 2026/7/17 */ public class HomeWork02 { public static void main(String[] args) { /* 选出来最小的元素,和第1个元素进行交换 每一轮外层循环,只交换1次。 */ int[] arr={56, 23, 89, 12, 45, 67, 34, 78}; //外层循环,i既是已排序区间的末尾边界,也是当前要确定的位置 for (int i = 0; i < arr.length-1; i++) { //假设当前没有排序的区间的第1个元素是最大的。 int maxIndex=i; //现在 maxIndex==i for (int j = i+1; j arr[maxIndex]){ maxIndex=j; } } //如果最大值不在i的位置,就就说明maxIndex!=i 说明上面的if语句里的代码起作用了 //说明 数组中有比当前maxIndex对应的元素还大的元素。所以就要交换位置 if (maxIndex!=i){ arr[maxIndex]= arr[maxIndex]+arr[i]; arr[i]=arr[maxIndex]-arr[i]; arr[maxIndex]= arr[maxIndex]-arr[i]; } } } }