Part2-->排序算法类模板

算法第四版第二章排序需要复用的代码的模板。

其中 algs4 是算法这本书作者自己写的一个类库,包含了一些常用的简单的方法。

ps : less()比较大小的方法

  exch()交换两个变量的值的方法

  show()向控制台输出结果的方法

  isSorted()测试数组元素是否有序的方法

 1 import java.util.Scanner;
 2 
 3 import edu.princeton.cs.algs4.In;
 4 
 5 public class Example {
 6     public static void sort(Comparable[] a){
 7     }
 8     private static boolean less(Comparable v, Comparable w) {
 9         return v.compareTo(w) < 0;
10     }
11     private static void exch(Comparable[] a, int i, int j) {
12         Comparable t = a[i];
13         a[i] = a[j];
14         a[j] = t;
15     }
16     private static void show(Comparable[] a) {
17         for (int i = 0; i < a.length; i++) {
18             System.out.print(a[i] + "");
19             System.out.println();
20         }
21     }
22     private static boolean isSorted(Comparable[] a) {
23         for (int i = 0; i < a.length; i++) {
24             if(less(a[i], a[i-1]))
25                 return false;
26         }
27         return true;
28     }
29     public static void main(String[] args) {
30         String[] a = In.readStrings();
31         //sort(a);
32         assert isSorted(a);
33         show(a);
34     }
35 }

猜你喜欢

转载自www.cnblogs.com/stitchZsx/p/9846704.html
今日推荐