package com.cc; import java.util.Arrays; /** * @Author: cc * @Create: 2021/12/20 */ public class Bubble { public static void main(String[] args) { int [] array = {2,5,1,23,16,78,3}; bubble(array); } public static void bubble(int [] a){ for (int j = 0; j < a.length -1; j++) { //是否发生元素交换的标志 boolean swapped = false; //一轮冒泡 for (int i = 0; i < a.length - 1 - j ; i++) { if (a[i] > a[i + 1]){ int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } System.out.println("第"+ j + "轮冒泡" + Arrays.toString(a)); //假如没有发生交换,则跳出循环 if (!swapped){ break; } } } }
输出打印结果如下:
第0轮冒泡[2, 1, 5, 16, 23, 3, 78]
第1轮冒泡[1, 2, 5, 16, 3, 23, 78]
第2轮冒泡[1, 2, 5, 3, 16, 23, 78]
第3轮冒泡[1, 2, 3, 5, 16, 23, 78]
第4轮冒泡[1, 2, 3, 5, 16, 23, 78]