优化冒泡排序
代码实现:
import java.util.Arrays;
public class MaoPao {
public static void main(String[] args) {
int[] arr = {5,6,7,2,1,0,8,3};
sort(arr);
}
public static void sort(int[] arr) {
for(int i=0;i<arr.length-1;i++) {
boolean flag = false;
for(int j=0;j<arr.length-1;j++) {
if(arr[j]>arr[j+1]) {
exchange(arr,i,j);
flag = true;
}
}
System.out.println("第"+i+"轮"+Arrays.toString(arr));
if(!flag) {
break;
}
}
}
public static void exchange(int[] arr,int i,int j) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
|