2.1.25

question:

Insertion sort without exchanges. Develop an implementation of insertion sort that moves larger elements to the right one position with one array access per entry, rather than using exch(). Use SortCompare to evaluate the effectives of doing so.

answer:

//我没有用SortCompare比较算法性能,以后有空再加吧

import edu.princeton.cs.algs4.*;

public class Insertion
{
    public static void sort(Comparable[] a)
    {
        //冒泡前先保存于temp中,中间交换直接进行覆盖(所以要保存到temp中)操作,直到条件不满足时再用temp对该元素进行覆盖,从而没有交换
        int N = a.length;
        Comparable temp;
        for(int i = 1; i < N; i++)
        {
            temp = a[i];
            int j;
            for(j = i; j > 0 && less(temp, a[j-1]); j--)//此时应该比较temp和前一个元素j-1,而不是比较j和j-1
                a[j] = a[j-1];//覆盖操作
            a[j] = temp;
        }
    }
    
    private static boolean less(Comparable v, Comparable w)
    {
        return v.compareTo(w) < 0;
    }
    
    private static void show(Comparable[] a)
    {
        for(int i = 0; i < a.length; i++)
            StdOut.print(a[i] + " ");
        StdOut.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)
    {
        String[] a = In.readStrings();//CTRL + d
        sort(a);
        assert isSorted(a);
        show(a);
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9114198.html