两层循环,外层冒泡次数,内层依次比较
public static int[] sort(int[] array){ // 降序排列 for (int i = 0; i < array.length-1; i++) { for(int j = 0; j < array.length-i-1 ; j++){ if (array[j+1] > array[j]){ int temp = array[j+1]; array[j+1] = array[j]; array[j] = temp; } } } return array; }
public static int[] sort(int[] array){ // 降序排列 // 设置一个临时变量,标识没有意义的比较 boolean flag = false; for (int i = 0; i < array.length-1; i++) { for(int j = 0; j < array.length-i-1 ; j++){ if (array[j+1] > array[j]){ int temp = array[j+1]; array[j+1] = array[j]; array[j] = temp; flag = true; } } if (flag == false) break; } return array; }