• 0

[JAVA] Merge Sorted Files


Question

Hey,

I'm having an issue with trying to figure out how to take two text files that contain strings (sorted in ascending order), and merge them into a third text file that is also sorted in ascending order. The problem is I can't use arrays and I shouldn't have to sort the strings. Also, the two text files are not necessarily the same length.

I've tried several times, but I can't seem to figure it out. Mainly, what I can't figure out is how to simultaneously read the two files together and then compare each line as they come in. I've tried using compareTo which works, but I have it set up in a while loop which is reading both files at the same time (ie. while (fileReader1.hasNext() && fileReader2.hasNext()).

Anyone have any ideas?

Link to comment
https://www.neowin.net/forum/topic/874284-java-merge-sorted-files/
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Here's what I have so far, it sorts most of it all right but obviously it stops once one of the files reaches the end and won't continue.

import java.io.*;
import java.util.Scanner;

public class Merger
{
	public static void main(String[] args) throws IOException
	{
		String file1 = "list1.txt";
		String file2 = "list2.txt";
		String outFile = "list3.txt";
		String curString1, curString2, curString3, writeString1, writeString2, writeString3;
		int count1, count2, max;

		Scanner fileReader1 = new Scanner(new File(file1));
		Scanner fileReader2 = new Scanner(new File(file2));

		FileWriter fw = new FileWriter(outFile);
		BufferedWriter bw = new BufferedWriter(fw);
		PrintWriter out = new PrintWriter(bw);

		while (fileReader1.hasNext() && fileReader2.hasNext())
		{
			curString1 = fileReader1.next();
			curString2 = fileReader2.next();

			if (fileReader1.hasNext())
			{
				curString3 = fileReader1.next();
			}
			else
			{
				curString3 = fileReader2.next();
			}


			if (curString1.compareTo(curString2) < 0)
			{
				if (curString2.compareTo(curString3) < 0)
				{
					writeString1 = curString1;
					writeString2 = curString2;
					writeString3 = curString3;

					out.print(writeString1);
					out.println();
					out.print(writeString2);
					out.println();
					out.print(writeString3);
					out.println();
				}
				else if (curString2.compareTo(curString3) > 0)
				{
					writeString1 = curString1;
					writeString2 = curString3;
					writeString3 = curString2;

					out.print(writeString1);
					out.println();
					out.print(writeString2);
					out.println();
					out.print(writeString3);
					out.println();
				}
			}
			else if (curString2.compareTo(curString1) < 0)
			{
				if (curString1.compareTo(curString3) < 0)
				{
					writeString1 = curString2;
					writeString2 = curString1;
					writeString3 = curString3;

					out.print(writeString1);
					out.println();
					out.print(writeString2);
					out.println();
					out.print(writeString3);
					out.println();
				}
				else if (curString1.compareTo(curString3) > 0)
				{
					writeString1 = curString2;
					writeString2 = curString3;
					writeString3 = curString1;

					out.print(writeString1);
					out.println();
					out.print(writeString2);
					out.println();
					out.print(writeString3);
					out.println();
				}
			}
		}
		out.close();
	}
}

  • 0

Well the loop condition is wrong, you want to keep adding entries while one OR the other file has remaining entries, not AND. Basically the algorithm is:

while file1 or file2 has a remaining entry:
	if only one has an entry:
		add it to the new file
	if both have entries:
		take the smallest 
		add it to the new file

Of course you need to maintain some kind of counter for each file indicating what's the next entry and increment it when you take an entry.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft is adding some very useful features to Word, Teams, Outlook, and more by Usama Jawad Image via Microsoft Microsoft 365 is the Redmond tech firm's premier solution for Office apps and cloud storage, among other things. Microsoft offers both consumer- and enterprise-oriented subscriptions for this solution, enabling customers to take full advantage of cloud-powered capabilities, in contrast to the LTSC versions of Office. Microsoft 365 apps and services regularly receive new updates and the good thing is that Microsoft tracks them in a very transparent way on its public roadmap. The Redmond company has updated its Microsoft 365 Roadmap with a lot of items in the past week or so, and there are several interesting features there that may excite its customers. For starters, Word is getting a very useful utility that will likely help people writing detailed documents using the software. Microsoft is integrating third-party citation providers in the Reference tab, so that users can quickly add citations. This is being made available to GCC, GCC High, and Department of Defense (DoD) customers on desktop and web this month. There are several improvements on the way for Copilot Notebooks too. Users can customize the format, style, and duration of Audio Overviews in the application through natural language prompts. These Audio Overviews can then be saved on OneDrive so that they can be shared with others too. All of these capabilities are landing on the web next month. Speaking of Copilot, Microsoft is moving the navigation pane for Copilot Chat from the right side of the app to the left. Apart from retaining the existing features, this repositioning allows Microsoft to add new capabilities such as an All Conversations tab, while also streamlining the overall navigation experience. This is being implemented for all customers using Outlook and Teams on the web from next month. In the latter software, Microsoft is also introducing regional settings that gives controls over the app's language and datetime formats. This is being made available for all Teams customers on Android, iOS, desktop, and the web from next month. Meanwhile, the desktop version of Teams is exclusively gaining the ability next month to search for meetings and participants in the search bar and take actions directly from there. Available actions include viewing recaps, accessing the dedicated meetings tab, and RSVP-ing. Microsoft added 39 items to the Microsoft 365 Roadmap, so you can understand that the selection of items described above is only scratching the tip of the iceberg. Check out other upcoming capabilities like Universal Print enhancements and more Copilot improvements on the dedicated webpage here.
    • PC to remote Android phone possible?
    • The same idiots that provide their phone numbers and id to discord channels.
    • Wait, I thought there is no such thing as "eating disorder" and it is fat-phobic to say it!
  • Recent Achievements

    • Week One Done
      hhgygy earned a badge
      Week One Done
    • One Month Later
      hhgygy earned a badge
      One Month Later
    • One Year In
      NIKI77 earned a badge
      One Year In
    • Week One Done
      artistro08 earned a badge
      Week One Done
    • Dedicated
      Balaji Kumar earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      639
    2. 2
      ATLien_0
      237
    3. 3
      Xenon
      166
    4. 4
      neufuse
      144
    5. 5
      +FloatingFatMan
      122
  • Tell a friend

    Love Neowin? Tell a friend!