数据结构-插入排序法

  插入排序法 (Insert Sort) 是将数组中的元素,逐一与已排序好的数据作比较,再将该数组元素插入适当的位置。

演算过程

插入法分析

  1. 最坏及平均情况需比较 (n-1)+(n-2)+(n-3)+...+3+2+1=n(n-1)/2 次;时间复杂度为 O(n^2),最好情况时间复杂度为 O(n)。
  2. 插入排序是稳定排序法。
  3. 只需一个额外的空间,所以空间复杂度为最佳。
  4. 此排序法适用于大部分数据已经过排序或已排序数据库新增数据后进行排序的情况。
  5. 插入排序法会造成数据的大量搬移,所以建议在链表上使用。

example1:

/**
 * 插入排序法
 *
 */
public class InsertSort {

    public static void main(String[] args) {
        int data[] = new int[] {6, 4, 9, 8, 3};
        System.out.print("原始数据:");
        showData(data);
        insert(data);
        System.out.print("排序后的数据:");
        showData(data);
    }
    
    private static void insert(int data[]) {
        int i, j, tmp;
        for (i = 1; i < data.length; i++) {
            tmp = data[i];
            j = i;
            while (--j >= 0 && tmp < data[j]) {
                data[j+1] = data[j];
                data[j] = tmp;
            }
            showData(data);
        }
    }
    
    private static void showData(int data[]) {
        for (int i = 0; i < data.length; i++) {
            System.out.printf("[%d]", data[i]);
        }
        System.out.printf("%n");
    }

}

猜你喜欢

转载自www.cnblogs.com/qpliang/p/12687291.html