BubbleSort.java
package com.atguigu.Interview.study.base.er_fen_cha_zhao;
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
//int[] a = {5, 9, 7, 4, 1, 3, 2, 8};
int[] a = {5, 2, 7, 4, 1, 3, 8, 9};
//int[] a = {1, 2, 3, 4, 5, 7, 8, 9};
//bubble(a);
bubble_v2(a);
System.out.println(Arrays.toString(a));
}
public static void bubble_v2(int[] a) {
int n = a.length - 1;
while (true) {
int last = 0; // 表示最后一次交换索引位置
for (int j=0; j<n; j++) {
System.out.println("比较次数:"+j);
if (a[j] > a[j+1]) {
swap(a, j, j+1);
last = j;
}
}
n = last;
System.out.println("第轮冒泡:"+Arrays.toString(a));
if (n == 0) {
break;
}
}
}
public static void bubble(int[] a) {
for (int i=0; i<a.length-1; i++) {
boolean swapped = false;//是否发生了交换
for (int j=0; j<a.length-i-1; j++) {
System.out.println("比较次数:"+j);
if (a[j] > a[j+1]) {
swap(a, j, j+1);
swapped = true;
}
}
System.out.println("第"+i+"轮冒泡:"+Arrays.toString(a));
if (!swapped) {
break;
}
}
}
public static void swap(int[] a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}