这一段程序中String[] a=In.readStrings();应该如何从控制台输入,如何输出呢?(原题是算法第四版中的内容)import edu.princeton.cs.algs4.In;
//import edu.princeton.cs.algs4.In;
//import edu.princeton.cs.algs4.StdOut;
//选择排序
public class Selection {
public static void sort(Comparable[] a){
//将a[]升序排列
int N=a.length;
for(int i=0;i<a.length;i++){
//将a[i]与a[i+1..N]中的最小元素进行交换
int min=i;//最小元素索引
for(int j=i+1;i<N;j++)
if(less (a[j],a[min])) min=j;
exch(a,i,min);
}
}
private static boolean less(Comparable v,Comparable w){
return v.compareTo(w)<0;//v<w
}
private static void exch(Comparable []a,int i,int j){
Comparable t=a[i];
a[i]=a[j];
a[j]=t;
}
private static void show(Comparable[]a){
//单行中打印数组
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
public static boolean isSorted(Comparable []a){
//测试数组是否有序
for(int i=0;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);
}
}附上相关类的内容public final class In {
///// begin: section (1 of 2) of code duplicated from In to StdIn.
// assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A");
//// end: section (1 of 2) of code duplicated from In to StdIn.
private Scanner scanner;
/**
* Initializes an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
public static String[] readStrings() {
return new In().readAllStrings();
}
}
添加回答
举报
0/150
提交
取消