插入排序

插入排序应该是最简单的排序,其原理将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2),是稳定的排序方法。
插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素,但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。
给定数组A=(5,2,4,6,1,3),其排序过程如下:

这里写图片描述

Java代码:

public class InsertionSorter {
    private InsertionSorter() {}

    public static void sort(int[] a) {
        sort(a, 0, a.length);
    }

    public static void sort(int[] a, int fromIndex, int toIndex) {
        for (int j = fromIndex + 1; j < toIndex; j++) {
            int key = a[j];
            // insert a[j] to array a[0..j-1]
            int i = j - 1;
            while (i >= 0 && a[i] > key) {
                a[i + 1] = a[i];
                i--;
            }
            a[i + 1] = key;
        }
    }

    public static void sort(Object[] a) {
        sort(a, 0, a.length);
    }

    @SuppressWarnings("unchecked")
    public static void sort(Object[] a, int fromIndex, int toIndex) {
        for (int j = fromIndex + 1; j < toIndex; j++) {
            Object key = a[j];
            int i = j - 1;
            while (i >= 0 && ((Comparable)a[i]).compareTo(key) > 0) {
                a[i + 1] = a[i];
                i--;
            }
            a[i + 1] = key;
        }
    }

    public static <T> void sort(T[] a, Comparator<? super T> c) {
        sort(a, 0, a.length, c);
    }

    public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) {
        for (int j = fromIndex + 1; j < toIndex; j++) {
            T key = a[j];
            int i = j - 1;
            while (i >= 0 && c.compare(a[i], key) > 0) {
                a[i + 1] = a[i];
                i--;
            }
            a[i + 1] = key;
        }
    }

    public static void main(String[] args) {
        int[] a = {3, 2, 5, 1};
        sort(a);
        System.out.println(Arrays.toString(a));

        Integer[] a2 = {3, 2, 5, 1};
        sort(a2);
        System.out.println(Arrays.toString(a2));

        a2 = new Integer[]{3, 2, 5, 1};
        sort(a2, new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        System.out.println(Arrays.toString(a2));
    }
}

注:代码来自算法导论的Java实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值