排序(二)-冒泡排序

来源:互联网 发布:win7 key for mac 编辑:程序博客网 时间:2024/05/29 03:14

稳定性:stable sort

空间:In-place sort

最优复杂度:O(n^2)

最差复杂度:O(n^2)

伪代码:

Bubble_sort(A){    for i=1 to n        for j=n to i+1            if A[j] < A[j-1]                swap A[j] <-> A[j-1]   }
Java代码:

import java.util.Arrays;public class Main {public static void main(String[] args){Main m = new Main();int[] A = {1,2,3,5,4,7,9,1,2,5,3,2,1};m.bubbleSort(A);System.out.print(Arrays.toString(A));//输出:[1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 5, 7, 9]}public void bubbleSort(int[] A){for(int i = 0; i < A.length; ++i){for(int j = A.length - 1; j > i; --j){if(A[j] < A[j-1]){int temp = A[j];A[j] = A[j-1];A[j-1] = temp;}}}}}



0 0