结果
image.png我写的只是向后冒泡的例子,向前冒泡也很简单,自己改下就行了
完整代码
package Sort;
/**
* @author klr
* @create 2020-07-06-18:07
*/
public class BubbleSort {
public static void main(String[] args) {
BubbleSort bubbleSort = new BubbleSort();
int[] a1=new int[]{3,1,2,5,4,9,0,7};
int[] a=new int[]{0,1,2,3,5,4,9,7};//测试提前结束的例子
//正常排序
System.out.println("普通排序");
bubbleSort.sort(a1);
for (int i1 : a1) {
System.out.printf(i1+" ");
}
System.out.println();
System.out.println();
//提前结束
bubbleSort.sort(a);
for (int i : a) {
System.out.printf(i+" ");
}
}
//向后冒泡
public void sort(int[] array){
int temp=0;
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]){
flag=false;
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
if (flag) {
System.out.printf("排序%d次\n", i + 1);
return;
}
}
}
}
网友评论