public class ArrayDemo07 {public static void main(String[] args) {int[] a = {3,5,1,7,8,4};int[] sort = sort(a);System.out.println(Arrays.toString(sort)); // [1, 3, 4, 5, 7, 8]}/*每次将 最大 或 最小的数 后移*/public static int[] sort(int[] array){// 临时变量int temp = 0;// 外层循环for (int i = 0; i < array.length-1; i++) {// 内层循环,比较相邻的两个数 < > 可以控制是升序还是降序for (int j = 0; j < array.length-1-i; j++) {if (array[j+1]<array[j]){temp = array[j];array[j] = array[j+1];array[j+1] = temp;}}}return array;}// 排除无意义的比较public static int[] sortPlus(int[] array){// 临时变量int temp = 0;// 外层循环for (int i = 0; i < array.length-1; i++) {boolean flag = false; // 通过 flag 减少没有意义的比较for (int j = 0; j < array.length-1-i; j++) {if (array[j+1]<array[j]){temp = array[j];array[j] = array[j+1];array[j+1] = temp;flag = true;}}if (!flag){break;}}return array;}
}
https://www.bilibili.com/video/BV12J41137hu?p=58&spm_id_from=pageDriver