• 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

    • It's a Developer Beta 1 not even a Public or User Beta, I doubt any of the design is 100% finalized yet.
    • Was going to comment the same thing. It's SO annoying to have to go back to settings every time I install something new or some apps like discord update and the icon is hidden again.
    • XRECODE3 1.167 by Razvan Serea xrecode3 is a converter and audio-grabber which allows you to convert from mp3, mp2, wma, aiff, amr, ogg, flac, ape, cue, ac3, wv, mpc, mid, cue ,tta, tak, wav, wav(rf64), dts, m4a, m4b, mp4, ra, rm, aac, avi, mpg, vob, mkv, mka, flv, swf, mov, ofr, wmv, divx, m4v, spx, 3gp, 3g2, m2v, m4v, ts, m2ts, adts, shn, tak, xm, mod, s3m, it, mtm, umx, mlp to m4a, alac, ape, flac, mp3, mp4 (using NeroAAC), ogg, raw, wav, wav(rf64), wma, WavPack, mpc, mp2, Speex, ofr, ac3, aiff, tak, snd and Shorten formats. Command Line parameters are supported. XRECODE3 features: Works on XP, Vista, Windows 7, Windows 8, 10 32/64 bit versions and under Wine. Parallel conversion by utilizing power of multi-core CPUs. Support of embedded CUE sheets (for FLAC, WavPack, APE and TAK files). Support of mp4, mka chapters (can split mp4, mka by chapters to any supported format). Built-in Metadata editor with Cover Art support. Has support for LossyWav. Supports portable mode. Merge input files to one large audio file and create CUE sheet. Converting to many formats at once using "Multiple" output mode. Grabbing of multi-channel Audio CDs to the desired format at once. Informative and resizable UI suited even for netbooks. Extracting audio from flv, avi, mov etc. video files (multiple audio streams are supported). Can export/import Metadata to/from external file. Support for 24/32bit audio files. Multilanguage support. Currently program is available in Dutch, English, French, Japanese, Korean, Polish, Russian, Hungarian, Italian, Spanish, Spanish Traditional, Swedish, Brazilian Portuguese, German, Finnish, Bulgarian, Czech, Danish and Chinese (simplified) languages. What's new in XRECODE3: Native 64bit support. Added support for DSD/DST and DFF formats (including handling of SACD ISOs). Added option to extract audio without transcoding. Added option to encode several files to one multi-channel file. Added option to split file into individual track-per-channel for all available output formats. Added option to merge files per folder. Output and Metadata settings are now output format specific. Enhanced Metadata settings. Added support for multiple Cover pictures in Metadata editor. Added 32bit int/float output for formats which support them (e.g. WAV). Added dithering option in Output Settings. Added option to use EBUR128 in Normalize. Added option to Album Mode Normalize. Added option to configure Matrices under Output Settings. Added more output file pattern elements. Tabbed UI. CUE files are now displayed more nicely. Enhanced Shell Extension. XRECODE3 1.167 changelog: Added option to handle YEAR and DATE tags (under Settings/Metadata/Advanced). Updated to the latest qaac (2.85). Download: XRECODE3 v1.167 (64-bit) | Portable | ~30.0 MB (Shareware) Download: XRECODE3 v1.167 (32-bit) | Portable Link: XRECODE3 Homepage | XRECODE3 Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Hasleo Disk Clone 5.2.2.1 by Razvan Serea Hasleo Disk Clone is a free and all-in-one disk cloning software for Windows 11/10/8/7/Vista and Windows Server that can help you migrate Windows OS to another disk, clone one disk to another disk or clone one partition to another location quickly and efficiently. Completely Free Windows Migration and Disk/Partition Cloning Software Migrate Windows from one disk to another without reinstalling Windows, apps. Clone one disk to another and makes the data on 2 disks are exactly the same. Clone a partition to another location without losing any data. Easily adjust the size and location of the destination partition. Convert MBR to GPT or convert GPT to MBR by cloning. Creation of Windows PE emergency disk. Extremely fast cloning speed and multi-language support. Supported OS: Windows Vista/Server 2008 or later, fully compatible with GPT and UEFI. Note: Hasleo Disk Clone 5.2.2.1 changelog is not yet available. Download: Hasleo Disk Clone 5.2.2.1 | 28.8 MB (Freeware) Link: Hasleo Disk Clone Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Shouldn't using "High Performance" mode prevent c-states from initializing? Maybe AMD hasn't built a proper power plan for their x3d processors like they used to for their ryzen chips.
  • Recent Achievements

    • First Post
      Johnny Mrkvička earned a badge
      First Post
    • Week One Done
      viraltui earned a badge
      Week One Done
    • One Month Later
      serfegyed earned a badge
      One Month Later
    • Dedicated
      firey earned a badge
      Dedicated
    • Dedicated
      fettermanj earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      634
    2. 2
      ATLien_0
      229
    3. 3
      Michael Scrip
      218
    4. 4
      Xenon
      149
    5. 5
      Steven P.
      140
  • Tell a friend

    Love Neowin? Tell a friend!