Sometimes many file-based external sorting algorithms need to merge two ordered files. The following provides a simple C ++ implementation method. The specific idea is the same as that of merging two ordered Single-Chain tables.
Void merge_file (const string & file_in_name1, const string & file_in_name2, const string & file_out_name) {// open two input files and one output file ifstream fin1, fin2; fin1.open (release (), IOS: In | IOs: Binary); fin2.open (file_in_name2.c_str (), IOS: In | IOs: Binary); ofstream fout; fout. open (file_out_name.c_str (), IOS: Out | IOs: Binary); // read the first number of int temp1 and temp2 in each file; fin1.read (reinterpret_cast <char *> (& temp1), sizeof (int ); Fin2.read (reinterpret_cast <char *> (& temp2), sizeof (INT); // forward in two files, each time, only a small number of two files is selected and added to the end of the output file while (true) {If (temp1 <= temp2) {fout. write (reinterpret_cast <const char *> (& temp1), sizeof (INT); // read the last number of objects again, ensure that all data in each file is read. Fin1.read (reinterpret_cast <char *> (& temp1), sizeof (INT); If (fin1.eof () {break ;}} else {fout. write (reinterpret_cast <const char *> (& temp2), sizeof (INT); fin2.read (reinterpret_cast <char *> (& temp2), sizeof (INT )); if (fin2.eof () {break ;}} if (! Fin1.eof () {While (true) {// the other file has been read, indicating that the last integer read in the current file has not been written, so it must be written first. Fout. write (reinterpret_cast <const char *> (& temp1), sizeof (INT); fin1.read (reinterpret_cast <char *> (& temp1), sizeof (INT )); if (fin1.eof () {break; ;}} elsewhile (true) {fout. write (reinterpret_cast <const char *> (& temp2), sizeof (INT); fin2.read (reinterpret_cast <char *> (& temp2), sizeof (INT )); if (fin2.eof () {break ;}} fin1.close (); fin2.close (); fout. close ();}
int main( void ) {vector<int> a;push_rand(a);sort(a.begin(),a.end());write_data_to_file(a,"data1.txt");print_file("data1.txt");a.clear();push_order(a,100);write_data_to_file(a,"data2.txt");print_file("data2.txt");merge_file("data1.txt","data2.txt","data.txt");print_file("data.txt");return 0;}
The main function uses functions such as push_rand. They are all written for testing and are not very important. It is easy to implement and will not be listed one by one. This function can be used to merge sort files in two ways. K-channel merge algorithms must be recorded. As shown in the following blog.