[go: up one dir, main page]

0% found this document useful (0 votes)
42 views3 pages

Merge Sort Assignment

Working of merge sort
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views3 pages

Merge Sort Assignment

Working of merge sort
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

G Sai Vamsi

190330079
CSE-A

2.

Consider 2 files abc.txt and xyz.txt having data in sorted order (descending order).
Write a java program to read data from both the files and sort them in (descending
order) using merge sort and store the sorted data in a file named sortfile.txt

import java.io.*;
public class SortFile{
public static void sortedMerge(int a[], int b[],int c[], int n,int m){
int i = 0, j = 0, k = 0;
while(i<n&&j<m){
if(a[i]>b[j])c[k++]=a[i++];
else c[k++]=b[j++];
}
for(;i<n;i++)c[k++]=a[i];
for(;j<m;j++)c[k++]=b[j];
}
public static void main(String[] args)throws Exception{
int a[]=new int[100];
int b[]=new int[100];
int c[]=new int[100];
int i=0,n,m;
File file = new File("D:\\abc.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null){
a[i++]=Integer.parseInt(st);
}n=i;
file = new File("D:\\xyz.txt");i=0;
BufferedReader bb = new BufferedReader(new FileReader(file));
while ((st = bb.readLine()) != null){
b[i++]=Integer.parseInt(st);
}m=i;
sortedMerge(a,b,c,n,m);
FileWriter fw=new FileWriter("D:\\Sortfile.txt");
fw.write("Sorted merged list:\n\n");
for (i=0;i<n+m;i++)
fw.write(c[i]+" ");
fw.close();
}
}
G Sai Vamsi
190330079
CSE-A

You might also like