之前做某公司面试,题目:分别从2个文本中逐行读出每行只有一个数的序列(已排序),对这两组数进行排序并输入到一个文件中。
题解思想:本身逻辑不难,只要涉及到读写文本,然后再进行排序,当这些组合在一起的时候,难免有些中间细节不好把握,现在写下我的解题思路和代码,我是一种比较顺序,略显笨拙的方法,大家如果有优化可以积极提意见。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
public class io_text_sort {
//读文件,排序,写入
/**
* @param args
*/
//read
public static LinkedList<String> read(String filename){
LinkedList<String> list = new LinkedList<String>();
File file =new File(filename);
if (file.exists() && file.isFile()) {
try{
BufferedReader input = new BufferedReader(new FileReader(file));
String text;
while((text = input.readLine()) != null)
list.add(text);
input.close();
}
catch(IOException ioException){
System.err.println("File Error!");
}
}
return list;
}
//write
public static void write(int[] list,String filename){
File out =new File(filename);
if (out.exists()) {
out.delete();
}
try {
if (out.createNewFile()) {
BufferedWriter output = new BufferedWriter(new FileWriter(out));
for (int i = 0; i < list.length; i++) {
output.write(list[i] + "\r\n");
}
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//merge
public static int[] numberMerge(int[] a,int[] b){
int m=a.length;
int n=b.length;
int k=m+n;
int i=m-1;
int j=n-1;
int[] newarr=new int[k];
k--;
while(i>=0&&j>=0){
if(a[i]>b[j])
newarr[k--]=a[i--];
else
newarr[k--]=b[j--];
}
if(i>j){
while(i>=0)
newarr[k--]=a[i--];
}else{
while(j>=0)
newarr[k--]=a[j--];
}
return newarr;
}
//String array to int array
public static int[] tran(String[] st){
int[] num=new int[st.length];
for(int i=0;i<st.length;i++){
num[i] =Integer.parseInt(st[i]);}
return num;
}
//main
public static void main(String[] args) {
LinkedList<String> list1 = new LinkedList<String>();
LinkedList<String> list2 = new LinkedList<String>();
list1=read("c:/a.txt");
list2=read("c:/b.txt");
String[] num1 = list1.toArray(new String[0]);
String[] num2 = list2.toArray(new String[0]);
int[] merge=new int[num1.length+num2.length];
merge=numberMerge(tran(num1),tran(num2));
write(merge,"c:/merge.txt");
//非常棒。。。。哈哈
}
}