冒泡排序算法
代码如下:
/**
* 数组的冒泡排序
* 将最大的冒到最后去
*/
class Demo9 {
public static void main(String[] args) {
int[] array = {1,2,5,3,7,5,9,8};
bubbleSort(array);
System.out.println(Arrays.toString(array));
/*for(int x: array){
System.out.println(x);
}*/
}
private static void bubbleSort(int[] array) {
for(int i = 0; i < array.length-1; i++){
boolean flag = true;
for(int j = 0; j < array.length-1-i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
flag = false;
}
}
if(flag){
break;
}
}
}
}
直接调Arrars.sort()算法进行排序:
代码如下:
class Demo10 {
public static void main(String[] args) {
int[] array = {1,4,2,5,6,2,8};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}