美文网首页
插入排序

插入排序

作者: jsjack_wang | 来源:发表于2017-10-16 19:19 被阅读0次
/**
 * 时间复杂度: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);
}

相关文章

网友评论

      本文标题:插入排序

      本文链接:https://www.haomeiwen.com/subject/tvsluxtx.html