StdOut和StdIn在http://algs4.cs.princeton.edu/code/ 下载algs4.jar 类库里

`````` import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdIn;
public class Insertion {
public static <T extends Comparable<T>>void sort(T [] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
for (int j = i; j > 0 && less(a[j], a[j-1]); j--) {
exch(a, j, j-1);
}
assert isSorted(a, 0, i);
}
assert isSorted(a);
}

// is v < w ?
private static <T extends Comparable<T>>boolean less(T v, T w) {
return v.compareTo(w) < 0;
}
//exchange a[i] and a[j]
private static <T extends Comparable<T>>void exch(T[] a, int i, int j) {
T swap = a[i];
a[i] = a[j];
a[j] = swap;
//is a[] sorted?
}
private static <T extends Comparable<T>>boolean isSorted(T [] a) {
for(int i = 0;i<a.length;i++)
if (less(a[i+1],a[i])) return false;
return true;
}
//is a[k]~a[m] sorted？
private static <T extends Comparable<T>>boolean isSorted(T [] a,int k,int m) {
for(int i = k;i<m;i++)
if (less(a[i+1],a[i])) return false;
return true;
}

// print array to standard output
private static <T extends Comparable<T>> void show(T [] a) {
for (int i = 0; i < a.length; i++) {
StdOut.print(a[i] + " ");
}
}

//the main method
public static void main(String[] args) {

sort(a);
show(a);

}
}
``````

4个回答

``````  public static void main(String[] args) {
System.setIn(new FileInputStream("tiny.txt"));
sort(a);
show(a);

}
``````

3 年多之前 回复

3 年多之前 回复

ystem.setIn把一个流写入控制台，并把它作为系统信息，