1_10.排序算法

1.冒泡排序

相邻两个数逐个做比较,每一轮比较完后的最大值一定产生在末尾
时间复杂度O(n^2), 空间复杂度O(n);

public class BubbleSort {

    public void bubbleSort(int[] array) {
        for (int endIndex = array.length - 1; endIndex > 0; endIndex--) {
            for (int startIndex = 0; startIndex < endIndex; startIndex++) {
                if (array[startIndex] > array[startIndex + 1]) {
                    swapNumbers(array, startIndex, startIndex + 1);
                }
            }
        }
        return;
    }

    private void swapNumbers(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
        return;
    }

    public static void main(String[] args) throws Exception {
        int[] array = new int[] { 3, 2, 4, 19, 23, -32 };
        BubbleSort bs = new BubbleSort();
        bs.bubbleSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

}

你可能感兴趣的:(1_10.排序算法)