java的插入排序算法学习

java的插入算法学习
实现代码:
   
   
public class Insertion {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static boolean less(Comparable v, Comparable m){
        return v.compareTo(m) < 0;
    }
    @SuppressWarnings({ "unused", "rawtypes" })
    private static void exch(Comparable [] a, int i, int j){
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
    @SuppressWarnings({ "unused", "rawtypes" })
    private static void show(Comparable [] a){
        System.out.println("排序之后:");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
    }
    @SuppressWarnings("rawtypes")
    public static boolean isSorted(Comparable [] a){
        //测试数组元素是否有序
        for (int i = 1; i < a.length; i++) 
            if (less(a[i], a[i-1])) 
                return false;
        return true;
    }
    @SuppressWarnings("rawtypes")
    public static void sort(Comparable [] a){
        int N = a.length;
        for (int i = 1; i < N; i++) {
            //将a[i]插入到a[-1],a[i-2],a[i-3]...之中
            for (int j = i; j > 0 && less(a[j], a[j-1]); j--) 
                exch(a, j, j-1);
        }
    }
    @SuppressWarnings("rawtypes")
    public static void main(String[] args) {
        //Comparable[] a = {49,38,65,97,76,13,27,49,78,34,12,64,1,8};
        String [] a = {"s","o","r","t","e","x","a","m","p","l","e"};
        System.out.println("排序之前:");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i]+" ");
        }
        System.out.println();
        sort(a);
        assert isSorted(a);
        show(a);
    }
}
     
     
排序之前:
s o r t e x a m p l e 
排序之后:
a e e l m o p r s t x   
算法分析:
  1. 直接插入排序是稳定的排序;
  2. 文件初态不同时,直接插入排序所耗费的时间有很大差异。若文件初态为正序,则每个待插入的记录只需要比较一次就能够找到合适的位置插入,故算法的时间复杂 度为O(n),这时最好的情况。若初态为反序,则第i个待插入记录需要比较i+1次才能找到合适位置插入,故时间复杂度为O(n2),这是最坏的情况,直接插入排序的时间复杂度为0(n2);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半路笙歌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值