冒泡排序(Bubble Sort)算得上是一个非常经典的排序算法,同时也是所有排序算法当中最简单、最基本的一种。其核心是通过多次的比较和交换来达到排序的目的。
其动态图如下:
算法流程:
(1)对数组中的各数据,依次比较相邻两个元素的大小。
(2)如果前面的数据大于后面的数据,就交换这两个数据。经过第一轮的多次比较排序后,便可将最小的数据排好。
(3)再用同样的方法把剩下的数据逐个进行比较,最后便可按照从小到大的顺序排好数组各数据。
=====以上流程文字摘自《Java常用算法手册》P119=====
核心代码如下:
void bubbleSort(int[] a) {
int temp;
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j+1]) { //将相邻两个数进行比较,较大的数往后冒泡
//交换两个数字
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
代码实例如下:
package cn.honda.sort;
public class BubbleSort {
static final int SIZE = 10;
public static void main(String[] args) {
int[] arr = new int[SIZE];
int i;
for (i = 0; i < SIZE; i++) {
arr[i] = (int)(100 + Math.random() * (100+1));
}
System.out.println("排序前的数组为:");
for (i = 0; i < SIZE; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
bubbleSort(arr);
System.out.println("排序后的数组为:");
for (i = 0; i < SIZE; i++) {
System.out.print(arr[i] + " ");
}
}
public static void bubbleSort(int[] a) {
int temp;
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j+1]) {//将相邻两个数进行比较,较大的数往后冒泡
//交换两个数字
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
System.out.print("第"+i+"步排序结果:");//输出每步排序的结果
for (int k = 0; k < a.length; k++) {
System.out.print(" " + a[k]); //输出排序后的结果
}
System.out.println();
}
}
}