2013-03-06 68 views
0

我将10 GB文件拆分为100000多个文件(几百字)(因为我在读到100000字时读到了这行)。合并排序具有可变字数的多个文件

private void splitInputFile(String path) { 
    try{ 
     File file=new File(path); 
     FileReader fr = new FileReader(file); 
     BufferedReader br = new BufferedReader(fr); 
     String temp; 
     temp = br.readLine(); 
     String fileName="fileName"; 
     int fileCount = 1; 
     while(temp!=null){ 
       //TODO Read 100000 words, sort and write to a file. Repeat for the entire file 
      if(wordsToBeSorted.size()<=100000){ 
       startCounting(temp); 
       temp=br.readLine(); 
      }//end of if -> place 100000+ words inside the list 
      else{ 
       Collections.sort(wordsToBeSorted); 
       fileName = "fileName"+fileCount; 
       fileCount++; 
       File splitFile = new File(fileName); 
       PrintWriter pr = new PrintWriter(splitFile); 
       for(String word:wordsToBeSorted){ 
        pr.write(word); 
        pr.write("\n");//check if this works -> 1 word per line 
       }//end of for 
      }//end of else    
     }//end of while 
     mergeSort(fileCount); 
    }//end of try 
    catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 


private void startCounting(String sb) { 
    StringTokenizer tokenizer = new StringTokenizer(sb);// Split by space 
    while (tokenizer.hasMoreTokens()) { 
     String text = tokenizer.nextToken(); 
     text = text.replaceAll("\\W", "");// Remove all symbols 
     if("".equals(text.trim())) 
      continue; 
     wordsToBeSorted.add(text); 
    } 

} 

现在我想知道如何对这些文件进行排序。我发现我应该做一个合并排序。考虑到每个splitFile可能会有不定数量的单词(100000多少个额外单词)的事实,是否可以进行包含可变词计数文件的合并排序?或者我应该按照其他方法来分割文件?

回答

1

是否有可能做一个合并排序,涉及可变字数的文件?

当然。我假设这里的目标是external sorting。只需打开所有输入文件(除非有真的很多,在这种情况下,您可能需要执行多次运行),请从每个文件中读取第一个单词。然后识别最小单词的输入,将其输入到输出中,并从该输入中读取下一个单词。关闭并移除任何变空的输入,除非您没有更多的输入。

如果您有很多输入,您可以使用heap来组织您的输入,并将下一个单词作为关键字。您将删除最小的对象,然后在进入下一个单词之后重新插入它。