So I had 2 different text files with values and I had to output them into 1 result file. After I did this (I believe in a not optimal way) I have to sort them like it's 1 array however I can't really do that because I outputted K array and J array separately. (26th line function where I output)
#include <iostream>
#include <fstream>
//
usingnamespace std;
//
constchar duom0[] = "klase.txt";
constchar duom1[] = "naujokai.txt";
constchar rez[] = "r.txt";
//
void read_f1(int &n, int K[])
{
ifstream in(duom0);
in >> n;
for(int i = 0; i != n; i++) in >> K[i];
in.close();
}
//
void read_f2(int &m, int N[])
{
ifstream in(duom1);
in >> m;
for(int i = 0; i != m; i++) in >> N[i];
in.close();
}
//
void output_F1_F2_data(int n, int m, int K[], int N[])
{
ofstream out(rez);
for(int i = 0; i != n; i++) out << K[i] << " ";
for(int j = 0; j != m; j++) out << N[j] << " ";
out.close();
}
//
int main()
{
int n, K[100], m, N[100];
read_f1(n, K);
read_f2(m, N);
output_F1_F2_data(n, m, K, N);
return 0;
}
the algorithm you want is the simple version of merge sort, which basically says take 2 sorted lists and peel off the topmost value from both lists, (print, in this case) the smallest, get the next value from the list you consumed the value from and repeat until all values are consumed (from both lists!)
you can do this in the print function if you just want the output to be in this format without actually storing it or combine the arrays etc. If you need this result for something else, you can store it into a 3rd array instead.
Make one array big enough to hold all the data. Put the data from the first file into that array. Put the data from the second file also into that array, but after the data from the first file.
Then sort the array using the std::sort function from <algorithm>
unless these are very, very large any tweaks will give only tiny bits of speed back.
memcpy is faster than your own loop, unless the compiler is smart enough to generate the same code either way, for the first loop. For the second one, I don't think the compiler could figure it out and memcpy directly would be microscopically faster.
there are 2 approaches I guess..
1) memcpy both copy loops and keep the print or
2) instead, print as you copy and eliminate the final loop.
what you have is fine so long as N+K < a billion or so and so long as you are not running on like a 20MHZ cpu or something tiny/ancient/whatever. Current CPUs are so good that minor inefficiencies can be ignored in most code.