Thursday, May 5, 2022

merging two unsorted lists from two files into a third file into sorted from

 #include <iostream>

#include <fstream>
using namespace std;
void swap(int &size, int arra[])
{
    int i, max1;
    for (i = 0; i < size; i++)
    {
        for (int j1 = i + 1; j1 < size; j1++) // checks greater between previous and next index and swaps the greater with smaller
        {
            if (arra[j1] < arra[i])
            {
                max1 = arra[i];
                arra[i] = arra[j1];
                arra[j1] = max1;
            }
        }
    }
}
void sortedMerge(int a[], int b[], int res[],
                 int n, int m) // Merge two arrays in unsorted manner
{
    // Concatenate two arrays
    int i = 0, j = 0, k = 0;
    while (i < n)
    {                  // iterate in first array
        res[k] = a[i]; // put each element in res array
        i += 1;
        k += 1;
    }
    while (j < m)
    {                  // iterate in the second array
        res[k] = b[j]; // put each element in res array
        j += 1;
        k += 1;
    }
}
int main()
{
    ifstream o1, o2;
    ofstream o3;
    int size1, size2, max1, max2;
    cout << "enter number of integers in first file\n";
    cin >> size1;
    cout << "enter number of integers in second file\n";
    cin >> size2;

    int arr[100];
    int i = 0;
    int arr1[100];
    int j = 0;

    int n1, n2;
    o1.open("newfile1.txt");
    o2.open("newfile2.txt");
    o3.open("newfile3.txt");

    while (o1 >> n1) // executes only if o1 is not at eof
    {
        arr[i] = n1;
        i++;
    }

    o1.close();
    swap(size1, arr);

    for (i = 0; i < size1; i++)
    {
        cout << "\n "
             << "arr-" << i + 1 << "  " << arr[i] << '\n';
    }
    while (o2 >> n2) // executes only if o2 is not at eof
    {
        arr1[j] = n2;
        j++;
    }
    o2.close();
    swap(size2, arr1);

    for (j = 0; j < size2; j++)
    {
        cout << "\n "
             << "arr(1)" << j + 1 << " " << arr1[j] << "\n";
    }
    int size3 = size1 + size2;
    int res[size3];                    // create res array to Concatenate both the array
    sortedMerge(arr, arr1, res, size1, size2); // call function to append and sort

    swap(size3, res);
    cout << "The sorted array is: "<<endl;
    for (int k = 0; k < size3; k++)
        cout << " " << res[k] << " ";
    cout << "\n";
   
    for ( int c = 0; c < size3; c++)
    {
        o3<<res[c]<<" ";
    }
   
    o3.close();

    return 0;
}

No comments:

Software scope

 In software engineering, the software scope refers to the boundaries and limitations of a software project. It defines what the software wi...

Popular Posts