java算法之直接插入排序

来源:互联网 发布:mac上好用的office软件 编辑:程序博客网 时间:2024/05/18 10:08

基本思想:
将一个记录插入到已排序好的有序数组中,从而得到一个新的有序数组,记录数增1的有序数组。即:先将数组的第1个记录看成是一个有序的子数组,然后从第2个记录逐个进行插入,直至整个数组有序为止。
代码

    public class InsertSort {    public static void insertSort(int[] array) {        int temp;        for (int i = 1; i < array.length; i++) {            for (int j = i; j > 0; j--) {                if (array[j] < array[j - 1]) {                    temp = array[j];                    array[j] = array[j - 1];                    array[j - 1] = temp;                }            }        }    }    public static void main(String[] args) {        int[] a = new int[] { 49, 38, 65, 97, 76, 13, 27, 50 };        insertSort(a);        for (int i : a)            System.out.print(i + " ");    }}

时间复杂度
O(n^2)—最坏
O(n^2)—平均
O(n) ——最好