从第一个元素开始,根据浮力(值)的和后面值比较小的不断交换,直到浮到不能再高的位置了,即合适的位置。

public class BubbleSort {
    public static void main(String[] args) {
        int[] toBeSorted = { 1, 3, 5, 2, 4, 6 };
        for (int i = 0; i < toBeSorted.length; i++) {
            for (int j = i + 1; j < toBeSorted.length; j++) {
                if (toBeSorted[i] > toBeSorted[j]) {
                    int t = toBeSorted[i];
                    toBeSorted[i] = toBeSorted[j];
                    toBeSorted[j] = t;
                }
            }
        }
        for (int p = 0; p < toBeSorted.length; p++) {
            System.out.print(toBeSorted[p]);
        }
        System.out.println();
    }
}

时间复杂度O(n^2)

results matching ""

    No results matching ""