Back

Merging data files

Merging data
Merging two files is the name given to taking both files and creating one new file out of them. For example, File one might contain: 1, 6, 9, 16 and 22, and file two might contain: 2, 5, 23, 33, 100. If you merge the files, you end up with one file containing: 1, 2, 5, 6, 9, 16, 22, 23, 33, and 100. The programmer would write a procedure to merge two files. One possible merge pseudo-code, trying hard to use the sequence, selection and iteration constructs, is as follows:

READ first data in file A
READ first data in file B
WHILE not (end of file A) and not (end of file B)
                IF A < B
                WRITE A to file C
                IF not (end of file A)
                                READ next data in file A
                ENDIF
                ELSE
                WRITE B to file C
                IF not (end of file B)
                                READ next data in file B
                ENDIF
                ENDIF
ENDWHILE
WRITE remaining records from file that is not empty to file C.

An example of merge using the above pseudo-code
See if you can follow the pseudo-code to do the following merge. We have used a trace table to help us. Two small colleges have just merged. They currently each have a file that holds details about the courses they offer. We require a program that can merge these two files into one file for the new ‘super college’. We will use the Primary Key of each course in the merging algorithm. Merge the following two sorted files:

File A: 3, 7, 18, 80
File B: 1, 10, 19, 70, 100, 280, 500, 600, 800

File A

File B    

Merged file C

3

1

1

3

10

1, 3

7

10

1, 3, 7

18

10

1, 3, 7, 10

18

19

1, 3, 7, 10, 18

80

19

1, 3, 7, 10, 18, 19

80

70

1, 3, 7, 10, 18, 19, 70

80

100

1, 3, 7, 10, 18, 19, 70, 80

-

100

1, 3, 7, 10, 18, 19, 70, 80, 100, 280, 500, 600, 800


Back