插入排序算法

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) {

    }
}

你可能感兴趣的:(算法)