ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

读书笔记-《数据结构与算法》-摘要2[冒泡排序]

2026/8/13 20:12:25 拓冰建站 浏览量
读书笔记-《数据结构与算法》-摘要2[冒泡排序]

冒泡排序

核心:冒泡,持续比较相邻元素,大的挪到后面,因此大的会逐步往后挪,故称之为冒泡。

在这里插入图片描述

public class BubbleSort {public static void main(String[] args) {int unsortedArray[] = new int[]{6, 5, 3, 1, 8, 7, 2, 4};bubbleSort(unsortedArray);System.out.println("After sort: ");for (int item : unsortedArray) {System.out.print(item + " ");}}public static void bubbleSort(int[] array) {int len = array.length;for (int i = 0; i < len; i++) {System.out.print("第" + (i+1) + "轮冒泡排序前:");for (int item : array) {System.out.print(item + " ");}System.out.println();// 每遍循环要处理的无序部分for (int j = 1; j < len - i; j++) {if (array[j - 1] > array[j]) {// 交换位置int temp = array[j - 1];array[j - 1] = array[j];array[j] = temp;}}}}
}

输出:

第1轮冒泡排序前:6 5 3 1 8 7 2 4 
第2轮冒泡排序前:5 3 1 6 7 2 4 8 
第3轮冒泡排序前:3 1 5 6 2 4 7 8 
第4轮冒泡排序前:1 3 5 2 4 6 7 8 
第5轮冒泡排序前:1 3 2 4 5 6 7 8 
第6轮冒泡排序前:1 2 3 4 5 6 7 8 
第7轮冒泡排序前:1 2 3 4 5 6 7 8 
第8轮冒泡排序前:1 2 3 4 5 6 7 8 
After sort: 
1 2 3 4 5 6 7 8