(算法 第四版)排序算法类的模板

来源:互联网 发布:windows 7永久激活 编辑:程序博客网 时间:2024/06/03 10:48
package algorithm;import edu.princeton.cs.algs4.In;public class Example{    /*     * 整理所有元素,使其有序排列     */    public static void sort(Comparable[] a){        //参见具体算法    }    /*     *判断大小,v>w时返回true;      */    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.println(a[i]+" ");        }    }    /*     * 测试数组元素是否有序     */    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();        sort(a);        assert isSorted(a);        show(a);    }}
原创粉丝点击