插入排序

2017-10-16  本文已影响0人  jsjack_wang
/**
 * 时间复杂度:n * n
 */
public static void insertionSort(int[] array) throws Exception {
    if (array == null) {
        throw new Exception("Array can`t be null.");
    }
    int temp;
    for (int index = 1; index < array.length; index ++) {
        in:for (int childIndex = index - 1; childIndex >= 0; childIndex --) {
            if (array[childIndex] > array[childIndex + 1]) {
                temp = array[childIndex + 1];
                array[childIndex + 1] = array[childIndex];
                array[childIndex] = temp;
            } else {
                break in;
            }
        }
    }
}

public static void main(String[] args) throws Exception {
    int[] array = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
    Utils.println(array);
    insertionSort(array);
    Utils.println(array);
}
上一篇 下一篇

猜你喜欢

热点阅读