插入排序算法

package Second_Sort;

import java.util.Random;

import static Second_Sort.Example.*;

public class Insertion {
    public static void sort(Comparable[] a){
        //将a[]按升序排列
        int N = a.length;
        for(int i = 1;i < N;i++){
            //将a[i]插入到a[i-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);
            }
        }
        show(a);
    }

    //提高插入排序的速度的方法:在内循环中将较大的元素都向右移动而不总是交换两个元素
    public static void sort2(Comparable[] a){
        int N = a.length;
        for(int i = 1;i < N;i++){
            int current = (Integer)a[i];
            for(int j = i;j >= 0;j--){
                if(j != 0 && less(current, a[j-1]))
                    a[j] = a[j-1];
                else {
                    a[j] = current;
                    break;
                }
            }
        }
        show(a);
    }

    public static void main(String[] args) {
        Integer[] a = new Integer[10000];
        Random random = new Random(47);
        for(int i = 0;i < 10000;i++){
            a[i] = random.nextInt(2000);
        }

        System.out.println("-----第一种插入排序-----");
        Long s = System.currentTimeMillis();
        sort(a);
        Long e = System.currentTimeMillis();
        Long time = e - s;
        System.out.println("排序时间为:" + time);

        System.out.println("-----第二种插入排序-----");
        s = System.currentTimeMillis();
        sort2(a);
        e = System.currentTimeMillis();
        time = e - s;
        System.out.println("排序时间为:" + time);
    }
}

其中,Example类如下:

package Second_Sort;

public class Example {
    public static boolean less(Comparable v, Comparable w){
        return v.compareTo(w) < 0;
    }

    public static void exch(Comparable[] a, int i, int j){
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    public static void show(Comparable[] a){
        for(int i = 0;i < a.length;i++){
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }

    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;
    }

    public static void main(String[] args) {

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值