排序算法类模版

  1. import edu.princeton.cs.algs4.In;
  2. import edu.princeton.cs.algs4.StdOut;
  3. public class Selection {
  4. public static void sort(Comparable[] a){
  5. }
  6. private static boolean less(Comparable v, Comparable w){
  7. return v.compareTo(w) < 0;
  8. }//比较v是否小于w
  9. private static void exch(Comparable[] a, int i, int j){
  10. Comparable t = a[i];
  11. a[i] = a[j];
  12. a[j] = t;
  13. }//元素交换
  14. private static void show(Comparable[] a){
  15. for(int i = 0; i < a.length; i++)
  16. StdOut.print(a[i] + " ");
  17. StdOut.println();
  18. }//单行打印
  19. public static boolean isSorted(Comparable[] a){
  20. for(int i = 1; i < a.length; i++){
  21. if(less(a[i],a[i-1])) return false;
  22. }
  23. return true;
  24. }//判断是否有序
  25. public static void main(String[] args){
  26. String[] a = In.readStrings();
  27. sort(a);
  28. assert isSorted(a);
  29. show(a);
  30. }
  31. }