how to merge 2 sorted arrays from 2 files into 1 file

Hi, can someone help me with the idea on how to merge 2 sorted array from 2 text files into 1 text files that contains all sorted element.with the complexity of O(N)

For example:

textFile1 textFile2
0 1
2 3
4 5

I have these 2 textfile contains sorted array.Then I need to create a third file that merge textFile1 and textFile2 and expected the result to be

textFile3
0
1
2
3
4
5
Last edited on
What do you have so far?
This pseudo-code should get you started:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  file1.read(rec1);  // attempt to read a record from each file
  file2.read(rec2);  // One or both files may be empty
  while (! (file1.eof(() && file2.eof())
  { //  We got a record from at least one file
     if (file1.eof())
     {   // add record from file2 to output
          outf.write (rec2);
          file2.read(rec2);   //  attempt to read another record from file2
          continue;
      }
      if (file2.eof())
      {  // we must of had a record from file1
          outf.write (rec1);  //  Add record from file1 to output
          file1.read (rec1);  //  Attempt to read another record from file1
          continue;
      }
      if (rec1 == rec2)
      {  //  Same value in both files
          outf.write (rec1);
          outf.write (rec2);
          file1.read (rec1); 
          file2.read (rec2);
          continue;
      }
      if (rec1 < rec2)
      {  outf.write (rec1); // Write rec1 to output
          file1.read(rec1);  // read another record from file1
          continue;
      }
      //  rec2 must be < rec1
      outf.write (rec2);
      file2.read (rec2);
    }  //  End loop 


A much shorter approach is the following:
1
2
3
4
5
    vector<int> v1, v2, v3;
    //  Read file1 into v1
    //  Read file2 into v2
    //  Use std::merge () to produce v3
    //  Write v3 to outf 

Last edited on
Another way to sort the data of two files that look to be composed of unique valued POD types.... Use a std::set container, open each file and sequentially read each data item, and write out to a file that automatically sorted data after reading (and closing) the input files.
http://www.cplusplus.com/reference/set/set/
Topic archived. No new replies allowed.