概念
冒泡排序 (BubbleSort)的基本概念是:依次比较相邻的两个数,将小数放在前面,大数放在后面。即在第一趟:首先比较第1个和第2个数,将小数放前,大数 放后。然后比较第2个数和第3个数,将小数放前,大数放后,如此继续,直至比较最后两个数,将小数放前,大数放后。至此第一趟结束,将最大的数放到了最 后。在第二趟:仍从第一对数开始比较(因为可能由于第2个数和第3个数的交换,使得第1个数不再小于第2个数),将小数放前,大数放后,一直比较到倒数第 二个数(倒数第一的位置上已经是最大的),第二趟结束,在倒数第二的位置上得到一个新的最大数(其实在整个数列中是第二大的数)。如此下去,重复以上过 程,直至最终完成排序。
Java实现1(向前冒泡)
import java.util.Arrays; public class Bubblesort { static void bubbleSort(int[] a) { int temp; { for (int i = 0; i < a.length; i++) { for (int j = a.length - 1; j > i; j--) { if (a[j] < a[j - 1]) { temp = a[j]; a[j] = a[j - 1]; a[j - 1] = temp; } } System.out.println(Arrays.toString(a)); } } } public static void main(String[] args) { int[] arr = { 12, 3, 5, 4, 78, 67, 1, 33, 1, 1, 1 }; bubbleSort(arr); System.out.println(Arrays.toString(arr)); } }
实现2 (向后冒泡)
import java.util.Arrays; public class BubbleSort3 { public static void main(String[] args) { int score[] = { 100, 25, 87, 23, 1, 69, 99, 3 }; for (int i = 0; i < score.length - 1; i++) { for (int j = 0; j < score.length - i - 1; j++) { if (score[j] > score[j + 1]) { // 把小的值交换到后面 int temp = score[j]; score[j] = score[j + 1]; score[j + 1] = temp; } } System.out.println("第" + (i + 1) + "次排序结果:" + Arrays.toString(score)); } System.out.println("最终排序结果:" + Arrays.toString(score)); } }
实现3(优化,提前结束排序)
import java.util.Arrays; public class BubbleSort1 { public static void main(String[] args) { int[] values = { 5, 2, 4, 1, 3 }; sort(values); Arrays.toString(values); } public static void sort(int[] values) { int temp; boolean exchange; for (int i = 0; i < values.length; i++) { exchange = false; for (int j = values.length - 1; j > i; j--) { if (values[j - 1] > values[j]) { temp = values[j - 1]; values[j - 1] = values[j]; values[j] = temp; exchange = true; } } if (!exchange) return; //本趟排序未发生交换,提前终止算法 System.out.println("第" + (i + 1) + "次:"+Arrays.toString(values)); } } } 参考链接: 1. http://baike.baidu.com/view/254413.htm 2. http://www.cnblogs.com/wuzhenbo/archive/2012/03/30/2423861.html