结构与算法之插入排序

一、插入排序

  什么是插入排序:插入排序是将一个值按大小插入到一个有序的数据中,插入值以后,数据仍然有序。

  插入排序的时间复杂度:用大O法表示是O(N^2).但是比冒泡排序和选择排序更加的快

  插入排序图解:

        

  具体java代码:

public class InsertSort {
    int[] array = null;

    @Test
    public void testInsertSort() {

        array = new int[5];

        array[0] = 45;
        array[1] = 22;
        array[2] = 33;
        array[3] = 43;
        array[4] = 34;

        int nElmes = array.length;
        for (int i = 1; i < nElmes; i++) {
            if (array[i - 1] > array[i]) {
                int temp = array[i];
                int j = i;
                while (j > 0 && array[j - 1] > temp) {
                    array[j] = array[j - 1];
                    j--;
                }
                array[j] = temp;
            }
        }

        System.out.println(Arrays.toString(array));
    }

}
原文地址:https://www.cnblogs.com/googlemeoften/p/4783724.html