冒泡排序

冒泡排序据说是最简单的排序, 但个人觉得选择排序更简单.

既然冒泡排序不是最简单的, 那冒泡排序几乎就没什么优点了.

 

程序代码:

package ganggong.algorithm.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by rick on 2015/3/8.
 */
public class BubbleSortTest {
    public static void main(String[] args) {
        BubbleSortTest sortTest = new BubbleSortTest();
        int[] array = {84, 32, 87, 24, 67, 52, 85, 13, 53, 48, 21, 95, 98, 21, 45, 12, 75, 72, 54, 62};
        sortTest.printArray(array);
        System.out.println("begin:");

        sortTest.bubbleSort(array);
    }

    private void bubbleSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    int t = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = t;
                }
            }
            printArray(array);
        }
        assertSorted(array);
    }

    private void printArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + "\t");
        }
        System.out.println();
    }

    private void assertSorted(int[] array) {
        boolean sorted = true;
        for (int i = 0; i < array.length - 1; i++) {
            if (array[i] > array[i + 1]) {
                sorted = false;
                break;
            }
        }
        if (!sorted) {
            throw new RuntimeException("Not sorted");
        }
    }
}

 

 

输出结果:

84 32 87 24 67 52 85 13 53 48 21 95 98 21 45 12 75 72 54 62
begin:
32 84 24 67 52 85 13 53 48 21 87 95 21 45 12 75 72 54 62 98
32 24 67 52 84 13 53 48 21 85 87 21 45 12 75 72 54 62 95 98
24 32 52 67 13 53 48 21 84 85 21 45 12 75 72 54 62 87 95 98
24 32 52 13 53 48 21 67 84 21 45 12 75 72 54 62 85 87 95 98
24 32 13 52 48 21 53 67 21 45 12 75 72 54 62 84 85 87 95 98
24 13 32 48 21 52 53 21 45 12 67 72 54 62 75 84 85 87 95 98
13 24 32 21 48 52 21 45 12 53 67 54 62 72 75 84 85 87 95 98
13 24 21 32 48 21 45 12 52 53 54 62 67 72 75 84 85 87 95 98
13 21 24 32 21 45 12 48 52 53 54 62 67 72 75 84 85 87 95 98
13 21 24 21 32 12 45 48 52 53 54 62 67 72 75 84 85 87 95 98
13 21 21 24 12 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98
13 21 21 12 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98
13 21 12 21 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98
13 12 21 21 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98
12 13 21 21 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98
12 13 21 21 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98
12 13 21 21 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98
12 13 21 21 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98
12 13 21 21 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98
12 13 21 21 24 32 45 48 52 53 54 62 67 72 75 84 85 87 95 98

 

你可能感兴趣的:(算法,冒泡排序)