Java Reference
In-Depth Information
26
else
{
27 intFromF2 = f2.readInt();
28 }
29 }
30 }
31
32
while
(f1.available() >
0
&& f1Count++ < segmentSize) {
33 f3.writeInt(f1.readInt());
34 }
35
36
while
(f2.available() >
0
&& f2Count++ < segmentSize) {
37 f3.writeInt(f2.readInt());
38 }
39 }
remaining
f1
segment
remaining
f2
segment
23.8.3 Combining Two Phases
Listing 23.16 gives the complete program for sorting
int
values in
largedata.dat
and storing
the sorted data in
sortedfile.dat
.
L
ISTING
23.16
SortLargeFile.java
1
import
java.io.*;
2
3
public class
SortLargeFile {
4
public static final int
MAX_ARRAY_SIZE =
100000
;
max array size
I/O stream buffer size
5
public static final int
BUFFER_SIZE =
100000
;
6
7
public static void
main(String[] args)
throws
Exception {
8
// Sort largedata.dat to sortedfile.dat
9 sort(
"largedata.dat"
,
"sortedfile.dat"
);
10
11
// Display the first 100 numbers in the sorted file
12 displayFile(
"sortedfile.dat"
);
13 }
14
15
/** Sort data in source file into target file */
16
public static void
sort(String sourcefile, String targetfile)
17
throws
Exception {
18
// Implement Phase 1: Create initial segments
19
int
numberOfSegments =
20
initializeSegments(MAX_ARRAY_SIZE, sourcefile,
"f1.dat"
);
create initial segments
21
22
// Implement Phase 2: Merge segments recursively
23
merge(numberOfSegments, MAX_ARRAY_SIZE,
merge recursively
24
"f1.dat"
,
"f2.dat"
,
"f3.dat", targetfile
);
25 }
26
27
/** Sort original file into sorted segments */
28
private static int
initializeSegments
29 (
int
segmentSize, String originalFile, String f1)
30
throws
Exception {
31
// Same as Listing 23.12, so omitted
32 }
33
34
private static void
merge(
int
numberOfSegments,
int
segmentSize,
35 String f1, String f2, String f3, String targetfile)
36
throws
Exception {
37
if
(numberOfSegments >
1
) {
38
mergeOneStep(numberOfSegments, segmentSize, f1, f2, f3);
merge one step
Search WWH ::
Custom Search