- package algorithm;
- public class BubbleSort {
- // 冒泡排序1
- public static void bubbleSort1(int[] a, int n) {
- for (int i = 0; i < n; i++) {
- for (int j = 1; j < n - i; j++) {
- if (a[j - 1] > a[j]) {
- swap(a, j - 1, j);
- }
- }
- }
- }
- // 冒泡排序2
- //下面对其进行优化,设置一个标志,如果这一趟发生了交换,则为true,
- //否则为false。明显如果有一趟没有发生交换,说明排序已经完成。
- public static void bubbleSort2(int[] a, int n) {
- boolean flag = true;
- while(flag) {
- flag = false;
- for (int i = 0; i < n; i++) {
- for (int j = 1; j < n - i; j++) {
- if (a[j - 1] > a[j]) {
- swap(a, j - 1, j);
- flag = true;
- }
- }
- }
- }
- }
- // 冒泡排序3
- public static void bubbleSort3(int[] a, int n) {
- int flag = n;
- while(flag > 0) {
- flag = 0;
- for (int i = 0; i < n; i++) {
- for (int j = 1; j < n - i; j++) {
- if (a[j - 1] > a[j]) {
- swap(a, j - 1, j);
- flag = j;
- }
- }
- }
- }
- }
- public static void main(String[] args) {
- int max = 10;
- int[] a = { 2, 4, 1, 5, 7, 6, 1, 9, 0, 2 };
- printArray(a, max);
- bubbleSort3(a, max);
- printArray(a, max);
- bubbleSort1(a, max);
- printArray(a, max);
- bubbleSort2(a, max);
- printArray(a, max);
- }
- private static void printArray(int[] a, int n) {
- for (int i = 0; i < n; i++) {
- System.out.print(a[i] + " ");
- }
- System.out.println();
- }
- private static void swap(int a[], int x, int y) {
- int t = a[x];
- a[x] = a[y];
- a[y] = t;
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/130220148710.html
来源: http://www.codesnippet.cn/detail/130220148710.html