Merge Sort 1 Write a program that will read each line from A

Merge Sort

1. Write a program that will read each line from A4.txt and store the numbers into an array.
2. Sort the number of that array using Merge sort algorithm (using recursion).
3. Show the output in file B4.txt.
Note: In total there will be 15 lines in B4.txt, where each line will contain a sorted array. First two lines are given as sample.

A4.txt:

Sample input:

41 53 97 67 62 82 93 54 34 11 62 29 16 96 61

95 25 62 75 90 18 51 41 54 94 7 96 5 17 95

Sample output:

11 16 29 34 41 53 54 61 62 62 67 82 93 96 97

5 7 17 18 25 41 51 54 62 75 90 94 95 95 96

Solution

#include <iostream>
#include<fstream>

using namespace std;
void Merge(int A[], int p, int q, int r)
{
int n1 = q - p + 1;
int n2 = r - q;
int L[n1+1], R[n2+1];
for(int i = 0; i < n1; i++)
L[i] = A[p + i];
for(int j = 0; j < n2; j++)
R[j] = A[q + j + 1];
L[n1] = 999;
R[n2] = 999;
int i = 0, j = 0;
for(int k = p; k <= r; k++)
if(L[i] <= R[j])
A[k] = L[i++];
else
A[k] = R[j++];
}
void MergeSort(int Array[], int p, int r)
{
int q;
if(p < r)
{
q = (p + r) / 2;
MergeSort(Array, p, q);
MergeSort(Array, q+1, r);
Merge(Array, p, q, r);
}
}
int main()
{
int Array[200],value,i=0,count=0,len=0;
ifstream infile;
ofstream outfile(\"B4.txt\");
infile.open(\"A4.txt\");
if (infile.is_open())
{
while (!infile.eof())
{
infile>>value;
Array[i]=value;
i++;
}
  
}
len=i;
infile.close();
  
//cout<<\"Elements before sorting: \";
  
/* for(int i = 0; i <Array.length(); i++)
cout<<Array[i]<<\" \";*/
cout<<endl;
MergeSort(Array, 0, len-1);
// cout<<\"Elements after sorting: \";
for(int i = 0; i < len-1; i++)
{
outfile<<Array[i]<<\" \";
count++;
if(count==10)
{
outfile<<endl;
count=0;
}
}
}
do create A4 file before you run the code

Merge Sort 1. Write a program that will read each line from A4.txt and store the numbers into an array. 2. Sort the number of that array using Merge sort algori
Merge Sort 1. Write a program that will read each line from A4.txt and store the numbers into an array. 2. Sort the number of that array using Merge sort algori

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site