Created
December 11, 2015 13:21
-
-
Save mkotsur/e00e7baeac7f855b2df9 to your computer and use it in GitHub Desktop.
MergeSort implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
public class MergesortFiles { | |
public static void main(String[] bla) throws Exception { | |
final int MAX_READ_STEP = 15; | |
final File f1 = new File("/tmp/test.txt"); | |
final File f2 = new File("/tmp/test2.txt"); | |
try (final Reader fr1 = new BufferedReader(new FileReader(f1)); | |
final Reader fr2 = new BufferedReader(new FileReader(f2))) { | |
while (true) { | |
fr1.mark(MAX_READ_STEP); | |
fr2.mark(MAX_READ_STEP); | |
final Integer i1 = readNextInt(fr1); | |
final Integer i2 = readNextInt(fr2); | |
if(i1 == null || i2 == null) { | |
Reader notEmptyReader = i1 == null ? fr2 : fr1; | |
notEmptyReader.reset(); | |
printTheRest(notEmptyReader); | |
return; | |
} | |
if(i1 >= i2) { | |
System.out.println(i2); | |
fr1.reset(); | |
} else { | |
System.out.println(i1); | |
fr2.reset(); | |
} | |
} | |
} | |
} | |
private static void printTheRest(Reader r) throws IOException { | |
while (true) { | |
final Integer i = readNextInt(r); | |
if (i == null) { | |
break; | |
} | |
System.out.println(i); | |
} | |
} | |
private static Integer readNextInt(Reader fr) throws IOException { | |
char c; | |
final StringBuilder sb = new StringBuilder(); | |
do { | |
int i = fr.read(); | |
if(i == -1) { | |
return null; | |
} | |
c = (char)i; | |
if (c == ' ' || c == '\n') { | |
break; | |
} | |
sb.append(c); | |
} while (fr.ready()); | |
return Integer.parseInt(sb.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment