Sorting Partially Sorted Data


Sorting Partially Sorted Data

Anna
Today we’re looking at a sorting problem with a useful twist: some of the data is already sorted. A textbook company has bought another company, and we need to merge their email lists. One list is sorted by email address; the other is sorted by domain. The final list must be sorted by email address.

Maria
Before choosing an algorithm, let’s ask what part of the story matters. If we’re sorting by email address, the data could be any kind of values we can compare. So we can write a general program for merging sorted and unsorted data rather than making it specifically about email addresses.

Anna
Right. But if the requested order were by domain name, the fact that these values are email addresses would matter, because we’d need to compare their domains. Looking for that kind of abstraction helps make programs reusable.

Maria
Let’s call the larger, already-sorted list sortedData and the smaller, unsorted list unsortedData. The desired result is all their values together, in sorted order. And there’s an important complication: the lists can contain duplicate addresses, including an address that appears in both lists.

Anna
So we need to decide what the array and the output file should do about duplicates. One option is to search sortedData for each value in unsortedData and remove matches before sorting. Because sortedData is ordered, we could use a binary search, such as the utility in Java’s Arrays class.

Maria
Binary search is cheaper than linear search, but it still takes time, especially when sortedData is large. Another option is to sort all the values and remove duplicates while writing the output file. That’s easy when there aren’t many duplicates, but it could be a poor choice if almost everything is duplicated.

Anna
That’s a reminder that algorithm choices depend on the data. For now, we’ll use the simpler file-writing approach, while recognizing that a more systematic way to compare these trade-offs is a topic for a later data structures course.

Maria
And we should build duplicates into our test data instead of hoping they won’t occur. For example, put a j in both lists. Then the merged array should contain two j values, while the output file should contain only one.

Anna
Next, the file format. A practical format is to put the number of addresses first, followed by one address per line. Since the count is available immediately, the program can allocate an array of exactly the right size and read the data once, rather than first scanning the file to find its length and then reading it again.

Maria
That format also makes boundary cases clear. If a list has no data, its file should contain the count zero—not simply be an empty file, which would violate the format. We should also test cases with no unsorted data, just one value in either list, and one value in both.

Anna
The simplest possible implementation would put everything into one array and call Arrays.sort. That may be a reasonable choice if the main constraint is writing the program quickly. But these lists may be enormous, and sorting from scratch ignores the useful fact that one list is already ordered.

Maria
So let’s adapt algorithms we know. Selection sort repeatedly finds the smallest remaining value and places it in the next result position. At each step here, the candidate minimum might be the next value in sortedData or any of the values in unsortedData.

Anna
Once selection sort starts swapping, values from the sorted portion do move around. That sounds as though we might lose the benefit of having sortedData, but the key observation is that a displaced value is moved into a position that is still beyond the part of the array we’ve already processed. We can still use the remaining ordered values effectively.

Maria
The selection-sort adaptation needs two phases to search: when the current position is in the sorted portion, search the unsorted portion for a smaller value; when the current position is in the unsorted portion, search the remaining unsorted values. It can be more complicated to code, and complicated algorithms are harder to implement correctly.

Anna
Insertion sort offers another approach. It begins with a sorted group and inserts unsorted values into their proper positions one at a time. Here, we could start insertion sort at the boundary between the two lists, treating the existing sorted list as the initial sorted group.

Maria
That can require very little code change—essentially changing the starting point of a loop. But inserting values may involve many shifts or swaps. With data sets that could contain millions of values, that cost matters.

Anna
The third idea is a two-finger merge. First, sort the smaller list, then compare the next unprocessed value from each sorted list and move the smaller one into a result array. For example, if the smaller list becomes j, k, u, we compare its j with the first value in the other list.

Maria
As the comparison proceeds, we only need to look at the current front of each list. If one front value is smaller, we copy it into the result and advance on that list. But this approach requires a second array to hold the merged result.

Anna
That extra array could double the storage needed. With enormous lists, the program might not have enough memory to run, so that can be a deal-breaker. In this situation, selection sort and insertion sort are more attractive because they use one array.

Maria
Between those two, insertion sort is easier to adapt, while selection sort may be more efficient. Since the point of this exercise is to be more efficient than simply sorting everything from scratch, we’ll choose selection sort, while acknowledging that the choice is a trade-off.

Anna
Now consider the method design. It might seem convenient to write one method that reads a file into an array, then call it twice. But that would create two arrays and then require another place to combine the data, increasing storage.

Maria
We could instead make one method read both files into one array. The difficulty is that the caller also needs to know where the first file’s values end and the second file’s values begin. Returning just the array doesn’t also return the first file’s size.

Anna
We could write another method to find that boundary, but that would mean extra work. The chosen design reads the two counts in main, then passes both scanners and both sizes to a readFiles method. That method returns one combined array. It’s not the prettiest signature, but it meets the storage and efficiency goals.

Maria
We also need a method to save the result. It receives an output filename and the data array, and it must account for duplicates when writing. The central algorithm method receives the array and the size of the original sorted portion, because that boundary tells it where to begin its search.

Anna
In main, the program asks the user for three filenames: the sorted input, the unsorted input, and the output. It opens scanners for the input files, reads each count first, and then consumes the rest of that line so the next read starts at the first data line.

Maria
Then main calls readFiles with the scanners and counts, closes both input files, calls the method that sorts the merged data, and finally saves the result. Closing files is an important part of the workflow, not something to leave until later.

Anna
The readFiles method allocates an array whose length is sortedSize plus unsortedSize. It uses one index across both loops: first it reads sortedSize lines from the sorted file, then it continues at the same index and reads unsortedSize lines from the other file.

Maria
That shared index needs to be declared before the first loop. If it were declared inside that loop, it wouldn’t be available to continue the second loop at the right position. The second loop’s stopping point is the total size of both lists.

Anna
We can also check whether each scanner has another line when we expect one. If a file is missing data or has extra data, it may be corrupted, and the user should receive an error message rather than silently getting a misleading result.

Maria
To test reading, we can first write the combined array to a file without sorting it. The save method uses a PrintWriter, writes the array length as the first line, writes each value on its own line, and closes the writer.

Anna
A successful run should produce a file with fourteen lines in this example: one line for the count and thirteen data values. Even before sorting, checking that the values and count are right helps test the reading and writing methods separately.

Maria
For the selection-sort method, the outer loop visits each position where the next minimum belongs. We initialize minIndex to the current index. Then we find the range to search: if we’re still in the original sorted portion, search the unsorted portion; if we’re already in the unsorted portion, search from the next position onward.

Anna
As we scan that range, we compare the candidate value with the current minimum and update minIndex when we find a smaller one. These are strings, so we can’t use the less-than operator. We use compareTo instead, and a negative result means the first string is smaller.

Maria
After the search, if minIndex differs from the current index, we swap those two strings using a temporary variable. If the indices are equal, there’s no need to swap. The method is a little more involved than a basic selection sort, so comments explaining the two search ranges are especially helpful.

Anna
The first run showed that the array was sorted correctly, but the output file still contained both copies of j. That exposed a missing step: duplicate removal belongs in the file-writing logic, not in the sorting method.

Maria
To avoid comparing the first value with an imaginary value before the array, handle it separately. If the array isn’t empty, write its first value. Then loop from index one onward, writing a value only when it differs from the previous value.

Anna
For strings, that comparison must use equals, with the condition checking that the values are not equal. Starting at index one also means we no longer need a special test for index zero inside the loop.

Maria
There’s one more subtle issue: the count at the top of the output file must reflect the number of unique values, not the original array length. So before writing the count, scan the sorted array and count the duplicates—each value equal to its predecessor is a duplicate.

Anna
Then the number written to the file is the array length minus the duplicate count. Be careful about the condition: when two adjacent strings are equal, increment the duplicate count. A mistaken not-equal condition would count the unique transitions instead and produce the wrong total.

Maria
With that corrected, the example produces twelve unique addresses from thirteen array entries. The array itself still has both copies of the shared j, while the file has one j and a count of twelve. That distinction is exactly why we planned the duplicate test in advance.

Anna
And there’s a broader lesson here: knowing how algorithms work gives us more building blocks. If we only knew how to call Arrays.sort, we might miss the chance to take advantage of partially sorted data. Understanding the details helps us adapt familiar techniques to new problems.

Maria
So the workflow is: abstract the task, identify duplicates and boundary cases, choose a file format that supports efficient reading, compare algorithm options and their costs, design methods around the storage constraints, and test each part—including the final unique-value count.

Anna
Exactly. The best solution isn’t always the shortest code or the most familiar API call. It depends on what matters most for the problem: runtime, storage, implementation complexity, and the actual shape of the data.

Ask anything
We've read this whole study set, so questions about it get the best answers.