自己组织一个字符串数组,里面的数据为一系列无序的字符串,选择一种最优的排序算法将其排序并将结果保存到"C:\Sort.TXT"文件中.
谢谢大家的指点,最好能有代码.
------解决方案--------------------
public class ArraySort {
public static void main(String[] args) {
String[] str = new String[]{ "bbb ", "www ", "eeee ", "sssss "};
Arrays.sort(str);
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
------解决方案--------------------
//: c11:DirList.java
// Displays directory listing.
// From 'Thinking in Java, 3rd ed. ' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
package org.luyang.collections;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Comparator;
public class Sort {
public static String sort1 = "BIG_TO_SMALL ";
public static String sort2 = "SMALL_TO_BIG ";
public static void main(String[] args) {
String[] list = new String[] { "C1 ", "A2 ", "B1 ", "E1 ", "D1 ", "F1 " };
Arrays.sort(list, new AlphabeticComparator1(sort2));
StringBuffer buf = new StringBuffer();
for (int i = 0; i < list.length; i++)
buf.append((list[i])).append( ", ");
String str = buf.toString();
BufferedReader br = new BufferedReader(new StringReader(str));
File file = new File( "C:\\Sort.TXT ");
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = null;
byte[] b = new byte[1024];
try {
while ((line = br.readLine()) != null) {
b = line.getBytes();
out.write(b);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class AlphabeticComparator1 implements Comparator {
String sort = null;
public AlphabeticComparator1(String sort) {
this.sort = sort;
}
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
if ( "SMALL_TO_BIG ".equalsIgnoreCase(sort)) {
return s1.toLowerCase().compareTo(s2.toLowerCase());
} else {
return s1.toLowerCase().compareTo(s2.toLowerCase()) * -1;
}
}
} // /:~